/**
 * BOMSection - 부품 구성 (BOM) 섹션
 */

import { Fragment } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { getPresetStyle } from '@/lib/utils/status-config';
import { NumberInput } from '@/components/ui/number-input';
import { CurrencyInput } from '@/components/ui/currency-input';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  Popover,
  PopoverAnchor,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Check, Package, Plus, Search, Trash2 } from 'lucide-react';
import type { BOMLine } from '@/types/item';
import type { BOMSearchState } from './types';

export interface BOMSectionProps {
  bomLines: BOMLine[];
  setBomLines: (lines: BOMLine[]) => void;
  bomSearchStates: Record<string, BOMSearchState>;
  setBomSearchStates: (states: Record<string, BOMSearchState>) => void;
  isSubmitting: boolean;
}

export default function BOMSection({
  bomLines,
  setBomLines,
  bomSearchStates,
  setBomSearchStates,
  isSubmitting,
}: BOMSectionProps) {
  return (
    <Card>
      <CardHeader>
        <div className="flex items-center justify-between">
          <CardTitle>부품 구성 (BOM)</CardTitle>
          <Button
            type="button"
            variant="outline"
            size="sm"
            onClick={() => {
              const newLine: BOMLine = {
                id: `bom-${Date.now()}`,
                childItemCode: '',
                childItemName: '',
                quantity: 1,
                unit: 'EA',
              };
              setBomLines([...bomLines, newLine]);
            }}
            disabled={isSubmitting}
          >
            <Plus className="h-4 w-4 mr-2" />
            BOM 품목 추가
          </Button>
        </div>
      </CardHeader>
      <CardContent>
        {bomLines.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-12 text-center">
            <Package className="h-16 w-16 text-muted-foreground mb-4 opacity-20" />
            <p className="text-sm text-muted-foreground mb-2">
              아직 부품 구성이 추가되지 않았습니다
            </p>
            <p className="text-xs text-muted-foreground">
              품목의 구성 부품, 원자재, 부자재를 추가할 수 있습니다
            </p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[280px]">품목코드 / 품목명 입력</TableHead>
                  <TableHead className="w-[180px]">품목명</TableHead>
                  <TableHead className="w-[150px]">규격</TableHead>
                  <TableHead className="w-[100px]">재질</TableHead>
                  <TableHead className="w-20">수량</TableHead>
                  <TableHead className="w-16">단위</TableHead>
                  <TableHead className="w-24 text-right">단가</TableHead>
                  <TableHead className="w-[180px]">비고</TableHead>
                  <TableHead className="w-16">삭제</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {bomLines.map((line) => {
                  // 각 라인별 검색 상태 가져오기
                  const searchState = bomSearchStates[line.id] || { searchValue: '', isOpen: false };
                  const searchValue = searchState.searchValue;
                  const searchOpen = searchState.isOpen;

                  // TODO: 실제 itemMasters 데이터로 교체 필요
                  // eslint-disable-next-line @typescript-eslint/no-explicit-any
                  const availableItems: any[] = [];

                  return (
                    <Fragment key={line.id}>
                      <TableRow>
                        <TableCell>
                          <div className="flex gap-1">
                            <Popover
                              open={searchOpen}
                              onOpenChange={(open) => {
                                setBomSearchStates({
                                  ...bomSearchStates,
                                  [line.id]: { ...searchState, isOpen: open },
                                });
                              }}
                            >
                              <div className="flex-1 relative">
                                <PopoverAnchor asChild>
                                  <Input
                                    placeholder="품목코드 또는 품목명 입력..."
                                    value={line.childItemCode || searchValue}
                                    onChange={(e) => {
                                      // 단순 입력만 처리 (서버 자동완성 준비)
                                      setBomSearchStates({
                                        ...bomSearchStates,
                                        [line.id]: { ...searchState, searchValue: e.target.value },
                                      });
                                    }}
                                    className="w-full"
                                    readOnly={!!line.childItemCode}
                                  />
                                </PopoverAnchor>
                                {line.childItemCode && (
                                  <div className="absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none">
                                    <Check className="h-4 w-4 text-green-600" />
                                  </div>
                                )}
                              </div>
                              <PopoverTrigger asChild>
                                <Button
                                  type="button"
                                  variant="outline"
                                  size="sm"
                                  onClick={() => {
                                    setBomSearchStates({
                                      ...bomSearchStates,
                                      [line.id]: { searchValue: '', isOpen: true },
                                    });
                                  }}
                                >
                                  <Search className="h-4 w-4" />
                                </Button>
                              </PopoverTrigger>
                              <PopoverContent
                                className="w-[400px] p-0 opacity-0 data-[state=open]:opacity-100 transition-opacity duration-150 delay-200"
                                side="bottom"
                                align="start"
                                sideOffset={4}
                                disableSlideAnimation
                              >
                                <Command>
                                  <CommandInput
                                    placeholder="품목코드 또는 품목명 검색..."
                                    value={searchValue}
                                    onValueChange={(value) => {
                                      setBomSearchStates({
                                        ...bomSearchStates,
                                        [line.id]: { ...searchState, searchValue: value },
                                      });
                                    }}
                                  />
                                  <CommandList>
                                    <CommandEmpty>검색 결과가 없습니다.</CommandEmpty>
                                    <CommandGroup>
                                      {availableItems.map((item) => (
                                        <CommandItem
                                          key={item.id}
                                          value={`${item.itemCode} ${item.itemName}`}
                                          onSelect={() => {
                                            // TODO: 품목 선택 시 데이터 채우기 로직
                                            const isBendingPart = item.partType === 'BENDING';

                                            setBomLines(
                                              bomLines.map((l) =>
                                                l.id === line.id
                                                  ? {
                                                      ...l,
                                                      childItemCode: item.itemCode || '',
                                                      childItemName: item.itemName || '',
                                                      specification: item.specification || '',
                                                      material: item.material || '',
                                                      unit: item.unit || 'EA',
                                                      unitPrice: 0, // TODO: pricing에서 가져오기
                                                      isBending: isBendingPart,
                                                      bendingDiagram: isBendingPart
                                                        ? item.bendingDiagram
                                                        : undefined,
                                                    }
                                                  : l
                                              )
                                            );
                                            setBomSearchStates({
                                              ...bomSearchStates,
                                              [line.id]: { searchValue: '', isOpen: false },
                                            });
                                          }}
                                          className="cursor-pointer"
                                        >
                                          <div className="flex items-center justify-between w-full">
                                            <div className="flex-1">
                                              <div className="flex items-center gap-2">
                                                <code className="text-xs bg-gray-100 px-2 py-0.5 rounded">
                                                  {item.itemCode}
                                                </code>
                                                <span className="text-sm">{item.itemName}</span>
                                                {item.specification && (
                                                  <span className="text-xs text-muted-foreground">
                                                    ({item.specification})
                                                  </span>
                                                )}
                                              </div>
                                            </div>
                                            <Badge variant="secondary" className="ml-2">
                                              {item.unit}
                                            </Badge>
                                          </div>
                                        </CommandItem>
                                      ))}
                                    </CommandGroup>
                                  </CommandList>
                                </Command>
                              </PopoverContent>
                            </Popover>
                          </div>
                        </TableCell>
                        <TableCell className="text-sm">{line.childItemName || '-'}</TableCell>
                        <TableCell className="text-sm text-muted-foreground">
                          {line.specification || '-'}
                        </TableCell>
                        <TableCell className="text-sm">
                          <Input
                            value={line.material || ''}
                            onChange={(e) => {
                              setBomLines(
                                bomLines.map((l) =>
                                  l.id === line.id ? { ...l, material: e.target.value } : l
                                )
                              );
                            }}
                            placeholder="재질"
                            className="w-full text-xs"
                          />
                        </TableCell>
                        <TableCell>
                          <NumberInput
                            value={line.quantity}
                            onChange={(value) => {
                              setBomLines(
                                bomLines.map((l) =>
                                  l.id === line.id ? { ...l, quantity: value ?? 0 } : l
                                )
                              );
                            }}
                            min={0}
                            step={0.01}
                            allowDecimal
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <Badge variant="secondary">{line.unit}</Badge>
                        </TableCell>
                        <TableCell>
                          <CurrencyInput
                            value={line.unitPrice || 0}
                            onChange={(value) => {
                              setBomLines(
                                bomLines.map((l) =>
                                  l.id === line.id ? { ...l, unitPrice: value ?? 0 } : l
                                )
                              );
                            }}
                            className="w-full"
                          />
                        </TableCell>
                        <TableCell>
                          <Input
                            value={line.note || ''}
                            onChange={(e) => {
                              setBomLines(
                                bomLines.map((l) =>
                                  l.id === line.id ? { ...l, note: e.target.value } : l
                                )
                              );
                            }}
                            placeholder="비고"
                            className="w-full text-xs"
                          />
                        </TableCell>
                        <TableCell>
                          <Button
                            type="button"
                            variant="ghost"
                            size="sm"
                            onClick={() => {
                              setBomLines(bomLines.filter((l) => l.id !== line.id));
                            }}
                          >
                            <Trash2 className="h-4 w-4 text-red-600" />
                          </Button>
                        </TableCell>
                      </TableRow>

                      {/* 절곡품인 경우 전개도 정보 표시 */}
                      {line.isBending && line.bendingDiagram && (
                        <TableRow>
                          <TableCell colSpan={9} className="bg-blue-50 p-4">
                            <div className="space-y-3">
                              <div className="flex items-center gap-2">
                                <Badge variant="outline" className={getPresetStyle('info')}>
                                  절곡품 전개도 정보
                                </Badge>
                              </div>

                              {/* 전개도 이미지 */}
                              <div>
                                <Label className="text-xs mb-2 block">전개도 이미지</Label>
                                <div className="border rounded-lg p-2 bg-white">
                                  <img
                                    src={line.bendingDiagram}
                                    alt="절곡 전개도"
                                    className="max-w-full h-auto max-h-[300px] object-contain mx-auto"
                                  />
                                </div>
                              </div>
                            </div>
                          </TableCell>
                        </TableRow>
                      )}
                    </Fragment>
                  );
                })}
              </TableBody>
            </Table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}