'use client';

import { Trash2, Image as ImageIcon } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { NumberInput } from '@/components/ui/number-input';
import { QuantityInput } from '@/components/ui/quantity-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import type { OrderDetailCategory, OrderDetailItem, OrderStatus } from '../types';
import {
  ORDER_STATUS_OPTIONS,
  ORDER_STATUS_LABELS,
  ORDER_STATUS_STYLES,
  MOCK_WORK_TEAM_LEADERS,
  MOCK_CATEGORIES,
  MOCK_ITEM_NAMES,
} from '../types';

interface OrderDetailItemTableProps {
  category: OrderDetailCategory;
  isEditMode: boolean;
  isViewMode: boolean;
  selectedItems: Set<string>;
  addCount: number;
  onAddCountChange: (count: number) => void;
  onAddItems: (count: number) => void;
  onDeleteSelectedItems: () => void;
  onDeleteAllItems: () => void;
  onCategoryChange: (field: keyof OrderDetailCategory, value: string) => void;
  onItemChange: (itemId: string, field: keyof OrderDetailItem, value: string | number) => void;
  onToggleSelection: (itemId: string) => void;
  onToggleSelectAll: () => void;
}

export function OrderDetailItemTable({
  category,
  isEditMode,
  isViewMode: _isViewMode,
  selectedItems,
  addCount,
  onAddCountChange,
  onAddItems,
  onDeleteSelectedItems,
  onDeleteAllItems,
  onCategoryChange,
  onItemChange,
  onToggleSelection,
  onToggleSelectAll,
}: OrderDetailItemTableProps) {
  const renderStatusBadge = (status: OrderStatus) => {
    return (
      <Badge className={ORDER_STATUS_STYLES[status]}>{ORDER_STATUS_LABELS[status]}</Badge>
    );
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-4">
        {/* 왼쪽: 발주 상세, 전체 N건 / N개 선택됨 / 선택삭제 */}
        <div className="flex items-center gap-4">
          <CardTitle className="text-lg">발주 상세</CardTitle>
          <span className="text-sm text-muted-foreground">전체 {category.items.length}건</span>
          {isEditMode && selectedItems.size > 0 && (
            <>
              <span className="text-sm text-muted-foreground">/</span>
              <span className="text-sm text-primary font-medium">{selectedItems.size}개 항목 선택됨</span>
              <Button
                variant="default"
                size="sm"
                onClick={onDeleteSelectedItems}
              >
                선택삭제
              </Button>
            </>
          )}
        </div>
        {/* 오른쪽 끝: 숫자, 추가, 카테고리, 🗑️ */}
        {isEditMode && (
          <div className="flex items-center gap-2">
            <QuantityInput
              min={1}
              value={addCount}
              onChange={(value) => onAddCountChange(value ?? 1)}
              className="w-16 h-8"
            />
            <Button variant="default" size="sm" onClick={() => onAddItems(addCount)}>
              추가
            </Button>
            <Select
              value={category.categoryId || 'none'}
              onValueChange={(value) => {
                onCategoryChange('categoryId', value);
                const cat = MOCK_CATEGORIES.find((c) => c.value === value);
                if (cat) {
                  onCategoryChange('categoryName', cat.label);
                }
              }}
            >
              <SelectTrigger className="w-32 h-8">
                <SelectValue placeholder="카테고리명" />
              </SelectTrigger>
              <SelectContent>
                {MOCK_CATEGORIES.map((opt) => (
                  <SelectItem key={opt.value} value={opt.value}>
                    {opt.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <Button
              variant="ghost"
              size="icon"
              onClick={onDeleteAllItems}
              className="text-destructive h-8 w-8"
              title="전체 삭제"
            >
              <Trash2 className="h-4 w-4" />
            </Button>
          </div>
        )}
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                {isEditMode && (
                  <TableHead className="w-[40px]">
                    <Checkbox
                      checked={
                        category.items.length > 0 &&
                        selectedItems.size === category.items.length
                      }
                      onCheckedChange={onToggleSelectAll}
                    />
                  </TableHead>
                )}
                <TableHead className="w-[50px] text-center">번호</TableHead>
                <TableHead className="w-[100px]">작업반장</TableHead>
                <TableHead className="w-[110px]">시공투입일</TableHead>
                <TableHead className="w-[110px]">시공완료일</TableHead>
                <TableHead className="w-[120px]">명칭</TableHead>
                <TableHead className="w-[120px]">제품</TableHead>
                <TableHead className="w-[70px] text-right">가로</TableHead>
                <TableHead className="w-[70px] text-right">세로</TableHead>
                <TableHead className="w-[150px]">항목명</TableHead>
                <TableHead className="w-[70px] text-right">수량</TableHead>
                <TableHead className="w-[60px]">단위</TableHead>
                <TableHead className="w-[100px]">비고</TableHead>
                <TableHead className="w-[60px] text-center">이미지</TableHead>
                <TableHead className="w-[110px]">발주일</TableHead>
                <TableHead className="w-[110px]">계획인수일</TableHead>
                <TableHead className="w-[110px]">실제인수일</TableHead>
                <TableHead className="w-[100px]">상태</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {category.items.length === 0 ? (
                <TableRow>
                  <TableCell
                    colSpan={isEditMode ? 18 : 17}
                    className="text-center text-muted-foreground py-8"
                  >
                    등록된 발주 품목이 없습니다.
                  </TableCell>
                </TableRow>
              ) : (
                category.items.map((item, index) => (
                  <TableRow key={item.id}>
                    {isEditMode && (
                      <TableCell>
                        <Checkbox
                          checked={selectedItems.has(item.id)}
                          onCheckedChange={() => onToggleSelection(item.id)}
                        />
                      </TableCell>
                    )}
                    <TableCell className="text-center">{index + 1}</TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Select
                          value={item.workTeamLeader || 'none'}
                          onValueChange={(value) =>
                            onItemChange(item.id, 'workTeamLeader', value)
                          }
                        >
                          <SelectTrigger className="h-8">
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {MOCK_WORK_TEAM_LEADERS.map((opt) => (
                              <SelectItem key={opt.value} value={opt.label}>
                                {opt.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      ) : (
                        item.workTeamLeader || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <DatePicker
                          value={item.constructionStartDate}
                          onChange={(date) =>
                            onItemChange(item.id, 'constructionStartDate', date)
                          }
                          size="sm"
                        />
                      ) : (
                        item.constructionStartDate || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <DatePicker
                          value={item.constructionEndDate}
                          onChange={(date) =>
                            onItemChange(item.id, 'constructionEndDate', date)
                          }
                          size="sm"
                        />
                      ) : (
                        item.constructionEndDate || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Input
                          value={item.name}
                          onChange={(e) => onItemChange(item.id, 'name', e.target.value)}
                          className="h-8"
                        />
                      ) : (
                        item.name || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Input
                          value={item.product}
                          onChange={(e) => onItemChange(item.id, 'product', e.target.value)}
                          className="h-8"
                        />
                      ) : (
                        item.product || '-'
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      {isEditMode ? (
                        <NumberInput
                          value={item.width}
                          onChange={(value) =>
                            onItemChange(item.id, 'width', value ?? 0)
                          }
                          className="h-8 text-right"
                        />
                      ) : (
                        item.width || '-'
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      {isEditMode ? (
                        <NumberInput
                          value={item.height}
                          onChange={(value) =>
                            onItemChange(item.id, 'height', value ?? 0)
                          }
                          className="h-8 text-right"
                        />
                      ) : (
                        item.height || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Select
                          value={item.itemName || 'none'}
                          onValueChange={(value) => onItemChange(item.id, 'itemName', value)}
                        >
                          <SelectTrigger className="h-8">
                            <SelectValue placeholder="선택" />
                          </SelectTrigger>
                          <SelectContent>
                            {MOCK_ITEM_NAMES.map((opt) => (
                              <SelectItem key={opt.value} value={opt.label}>
                                {opt.label}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      ) : (
                        item.itemName || '-'
                      )}
                    </TableCell>
                    <TableCell className="text-right">
                      {isEditMode ? (
                        <QuantityInput
                          value={item.quantity}
                          onChange={(value) =>
                            onItemChange(item.id, 'quantity', value ?? 0)
                          }
                          className="h-8 text-right"
                        />
                      ) : (
                        item.quantity
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Input
                          value={item.unit}
                          onChange={(e) => onItemChange(item.id, 'unit', e.target.value)}
                          className="h-8 w-14"
                        />
                      ) : (
                        item.unit || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Input
                          value={item.remark}
                          onChange={(e) => onItemChange(item.id, 'remark', e.target.value)}
                          className="h-8"
                        />
                      ) : (
                        item.remark || '-'
                      )}
                    </TableCell>
                    <TableCell className="text-center">
                      {item.imageUrl ? (
                        <Button variant="ghost" size="icon" className="h-8 w-8">
                          <ImageIcon className="h-4 w-4" />
                        </Button>
                      ) : (
                        '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <DatePicker
                          value={item.orderDate}
                          onChange={(date) =>
                            onItemChange(item.id, 'orderDate', date)
                          }
                          size="sm"
                        />
                      ) : (
                        item.orderDate || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <DatePicker
                          value={item.plannedDeliveryDate}
                          onChange={(date) =>
                            onItemChange(item.id, 'plannedDeliveryDate', date)
                          }
                          size="sm"
                        />
                      ) : (
                        item.plannedDeliveryDate || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <DatePicker
                          value={item.actualDeliveryDate}
                          onChange={(date) =>
                            onItemChange(item.id, 'actualDeliveryDate', date)
                          }
                          size="sm"
                        />
                      ) : (
                        item.actualDeliveryDate || '-'
                      )}
                    </TableCell>
                    <TableCell>
                      {isEditMode ? (
                        <Select
                          value={item.status}
                          onValueChange={(value) =>
                            onItemChange(item.id, 'status', value as OrderStatus)
                          }
                        >
                          <SelectTrigger className="h-8">
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            {ORDER_STATUS_OPTIONS.filter((o) => o.value !== 'all').map(
                              (opt) => (
                                <SelectItem key={opt.value} value={opt.value}>
                                  {opt.label}
                                </SelectItem>
                              )
                            )}
                          </SelectContent>
                        </Select>
                      ) : (
                        renderStatusBadge(item.status)
                      )}
                    </TableCell>
                  </TableRow>
                ))
              )}
              {/* 합계 행 */}
              {category.items.length > 0 && (
                <TableRow className="bg-muted/50 font-medium">
                  <TableCell colSpan={isEditMode ? 10 : 9} className="text-right">
                    합계
                  </TableCell>
                  <TableCell className="text-right">
                    {category.items.reduce((sum, item) => sum + item.quantity, 0)}
                  </TableCell>
                  <TableCell colSpan={isEditMode ? 7 : 7}></TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
