'use client';

import { Check } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { NumberInput } from '@/components/ui/number-input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import type { ProgressBillingItem } from '../types';
import { MOCK_BILLING_NAMES } from '../types';
import { formatNumber } from '@/lib/utils/amount';

interface ProgressBillingItemTableProps {
  items: ProgressBillingItem[];
  isViewMode: boolean;
  isEditMode: boolean;
  selectedItems: Set<string>;
  onToggleSelection: (itemId: string) => void;
  onToggleSelectAll: () => void;
  onApplySelected: () => void;
  onItemChange: (itemId: string, field: keyof ProgressBillingItem, value: string | number) => void;
}

export function ProgressBillingItemTable({
  items,
  isViewMode,
  isEditMode,
  selectedItems,
  onToggleSelection,
  onToggleSelectAll,
  onApplySelected,
  onItemChange,
}: ProgressBillingItemTableProps) {
  const allSelected = items.length > 0 && items.every((item) => selectedItems.has(item.id));

  const handleApply = () => {
    onApplySelected();
    toast.success('적용이 완료되었습니다.');
  };

  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between">
        <div className="flex items-center gap-2">
          <CardTitle className="text-lg">기성청구 내역</CardTitle>
          <span className="text-sm text-muted-foreground">
            전체 {items.length}건
          </span>
          {selectedItems.size > 0 && (
            <>
              <span className="text-sm text-muted-foreground">/</span>
              <span className="text-sm text-primary font-medium">{selectedItems.size}개 항목 선택됨</span>
            </>
          )}
        </div>
        {isEditMode && selectedItems.size > 0 && (
          <Button size="sm" onClick={handleApply}>
            <Check className="h-4 w-4 mr-1" />
            적용
          </Button>
        )}
      </CardHeader>
      <CardContent>
        <div className="overflow-x-auto">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50px]">
                  <Checkbox
                    checked={allSelected}
                    onCheckedChange={onToggleSelectAll}
                    disabled={isViewMode}
                  />
                </TableHead>
                <TableHead className="w-[60px]">번호</TableHead>
                <TableHead className="min-w-[120px]">시공번호</TableHead>
                <TableHead className="min-w-[100px]">명칭</TableHead>
                <TableHead className="min-w-[80px]">제품</TableHead>
                <TableHead className="min-w-[60px]">가로</TableHead>
                <TableHead className="min-w-[60px]">세로</TableHead>
                <TableHead className="min-w-[80px]">작업반장</TableHead>
                <TableHead className="min-w-[100px]">시공투입일</TableHead>
                <TableHead className="min-w-[100px]">시공완료일</TableHead>
                <TableHead className="min-w-[80px]">수량</TableHead>
                <TableHead className="min-w-[100px]">금회기성</TableHead>
                <TableHead className="min-w-[60px]">상태</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {items.map((item, index) => (
                <TableRow key={item.id}>
                  <TableCell>
                    <Checkbox
                      checked={selectedItems.has(item.id)}
                      onCheckedChange={() => onToggleSelection(item.id)}
                      disabled={isViewMode}
                    />
                  </TableCell>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>{item.constructionNumber}</TableCell>
                  <TableCell>{item.name}</TableCell>
                  <TableCell>
                    {isEditMode ? (
                      <Select
                        value={item.product}
                        onValueChange={(value) => onItemChange(item.id, 'product', value)}
                      >
                        <SelectTrigger className="min-w-[80px] w-auto">
                          <SelectValue placeholder="제품 선택" />
                        </SelectTrigger>
                        <SelectContent>
                          {MOCK_BILLING_NAMES.map((option) => (
                            <SelectItem key={option.value} value={option.label}>
                              {option.label}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    ) : (
                      item.product
                    )}
                  </TableCell>
                  <TableCell>
                    {isEditMode ? (
                      <NumberInput
                        value={item.width}
                        onChange={(value) => onItemChange(item.id, 'width', value ?? 0)}
                        className="min-w-[50px]"
                      />
                    ) : (
                      formatNumber(item.width)
                    )}
                  </TableCell>
                  <TableCell>
                    {isEditMode ? (
                      <NumberInput
                        value={item.height}
                        onChange={(value) => onItemChange(item.id, 'height', value ?? 0)}
                        className="min-w-[50px]"
                      />
                    ) : (
                      formatNumber(item.height)
                    )}
                  </TableCell>
                  <TableCell>{item.workTeamLeader}</TableCell>
                  <TableCell>{item.constructionStartDate}</TableCell>
                  <TableCell>{item.constructionEndDate || '-'}</TableCell>
                  <TableCell>
                    {isEditMode ? (
                      <NumberInput
                        value={item.quantity}
                        onChange={(value) => onItemChange(item.id, 'quantity', value ?? 0)}
                        className="min-w-[60px]"
                        step={0.01}
                        allowDecimal
                      />
                    ) : (
                      formatNumber(item.quantity)
                    )}
                  </TableCell>
                  <TableCell>{formatNumber(item.currentBilling)}</TableCell>
                  <TableCell>{item.status}</TableCell>
                </TableRow>
              ))}
              {items.length === 0 && (
                <TableRow>
                  <TableCell colSpan={13} className="text-center text-muted-foreground py-8">
                    데이터가 없습니다.
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </div>
      </CardContent>
    </Card>
  );
}
