'use client';

/**
 * 부품 조립 편집기
 *
 * 모델 폼 내부에서 사용 — 부품 목록 + 순서 변경 + 절곡 테이블
 */

import { useCallback, useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Plus,
  Trash2,
  ArrowUp,
  ArrowDown,
  RotateCcw,
  Edit,
  Copy,
  Loader2,
} from 'lucide-react';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { toast } from 'sonner';
import { BendingTable } from './BendingTable';
import { MaterialSummary } from './MaterialSummary';
import type { ComponentData, BendingData } from './types';
import { recalculateSums, getWidthSum } from './types';

interface PartListEditorProps {
  components: ComponentData[];
  onChange: (components: ComponentData[]) => void;
  readOnly?: boolean;
  onAddParts: () => void;
}

export function PartListEditor({
  components,
  onChange,
  readOnly = false,
  onAddParts,
}: PartListEditorProps) {
  const router = useRouter();

  // 다른이름저장: 기초관리 등록 페이지로 이동 (원본 데이터 + 새 이름)
  const [saveAsOpen, setSaveAsOpen] = useState(false);
  const [saveAsName, setSaveAsName] = useState('');
  const [saveAsIndex, setSaveAsIndex] = useState<number | null>(null);

  const handleOpenSaveAs = useCallback((index: number) => {
    setSaveAsIndex(index);
    setSaveAsName(components[index].itemName || '');
    setSaveAsOpen(true);
  }, [components]);

  const handleSaveAs = useCallback(() => {
    if (saveAsIndex === null || !saveAsName.trim()) return;
    const comp = components[saveAsIndex];
    sessionStorage.setItem('bending-save-as', JSON.stringify({
      name: saveAsName.trim(),
      material: comp.material || '',
      bendingData: comp.bendingData || [],
      width_sum: comp.width_sum || 0,
    }));
    setSaveAsOpen(false);
    router.push('/production/bending?mode=new&from=saveAs');
  }, [saveAsIndex, saveAsName, components, router]);

  // 부품 삭제
  const handleRemove = useCallback(
    (index: number) => {
      const updated = components
        .filter((_, i) => i !== index)
        .map((c, i) => ({ ...c, orderNumber: i + 1 }));
      onChange(updated);
    },
    [components, onChange]
  );

  // 전체 삭제
  const handleRemoveAll = useCallback(() => {
    onChange([]);
  }, [onChange]);

  // 순서 위로
  const handleMoveUp = useCallback(
    (index: number) => {
      if (index === 0) return;
      const updated = [...components];
      [updated[index - 1], updated[index]] = [updated[index], updated[index - 1]];
      onChange(updated.map((c, i) => ({ ...c, orderNumber: i + 1 })));
    },
    [components, onChange]
  );

  // 순서 아래로
  const handleMoveDown = useCallback(
    (index: number) => {
      if (index === components.length - 1) return;
      const updated = [...components];
      [updated[index], updated[index + 1]] = [updated[index + 1], updated[index]];
      onChange(updated.map((c, i) => ({ ...c, orderNumber: i + 1 })));
    },
    [components, onChange]
  );

  // 순서 초기화
  const handleResetOrder = useCallback(() => {
    onChange(components.map((c, i) => ({ ...c, orderNumber: i + 1 })));
  }, [components, onChange]);

  // 필드 인라인 수정
  const handleFieldChange = useCallback(
    (index: number, field: keyof ComponentData, value: string | number) => {
      const updated = [...components];
      updated[index] = { ...updated[index], [field]: value };
      onChange(updated);
    },
    [components, onChange]
  );

  // 부품별 절곡 데이터 수정
  const handleBendingDataChange = useCallback(
    (index: number, data: BendingData[]) => {
      const updated = [...components];
      updated[index] = {
        ...updated[index],
        bendingData: data,
        width_sum: getWidthSum(data),
      };
      onChange(updated);
    },
    [components, onChange]
  );

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold">
          절곡 부품 조립 ({components.length}개)
        </h3>
        {!readOnly && (
          <div className="flex gap-1">
            <Button type="button" size="sm" variant="default" onClick={onAddParts}>
              <Plus className="h-3.5 w-3.5 mr-1" />부품 추가
            </Button>
            <Button
              type="button"
              size="sm"
              variant="destructive"
              onClick={handleRemoveAll}
              disabled={components.length === 0}
            >
              전체 삭제
            </Button>
          </div>
        )}
      </div>

      {/* 순서 변경 버튼 */}
      {!readOnly && components.length > 1 && (
        <div className="flex gap-1 items-center text-xs text-muted-foreground">
          <Button type="button" size="sm" variant="outline" onClick={handleResetOrder}>
            <RotateCcw className="h-3 w-3 mr-1" />순서 초기화
          </Button>
          <span className="ml-2">※ 순서변경은 위/아래 버튼을 사용하세요</span>
        </div>
      )}

      {/* 부품 카드 리스트 */}
      {components.map((comp, index) => (
        <div key={`part-${index}`} className="border rounded-lg p-4 space-y-3 bg-white">
          {/* 부품 헤더 */}
          <div className="flex items-center gap-3 flex-wrap">
            <span className="inline-flex items-center gap-1 px-2 py-0.5 bg-blue-100 text-blue-800 rounded text-xs font-semibold">
              순서:{comp.orderNumber}
            </span>

            {readOnly ? (
              <span className="font-medium">{comp.itemName}</span>
            ) : (
              <Input
                value={comp.itemName}
                onChange={(e) => handleFieldChange(index, 'itemName', e.target.value)}
                className="h-7 w-[160px] text-sm"
                placeholder="부품명"
              />
            )}

            <span className="text-xs text-muted-foreground">재질:</span>
            {readOnly ? (
              <span className="text-sm">{comp.material}</span>
            ) : (
              <Input
                value={comp.material}
                onChange={(e) => handleFieldChange(index, 'material', e.target.value)}
                className="h-7 w-[120px] text-sm"
              />
            )}

            <span className="text-xs text-muted-foreground">수량:</span>
            {readOnly ? (
              <span className="text-sm">{comp.quantity}</span>
            ) : (
              <Input
                type="number"
                value={comp.quantity || ''}
                onChange={(e) => handleFieldChange(index, 'quantity', Number(e.target.value) || 0)}
                className="h-7 w-[60px] text-sm text-center"
              />
            )}

            <span className="text-xs text-muted-foreground">
              폭합: <span className="font-semibold text-blue-600">{comp.width_sum || 0}</span>
            </span>

            {/* 액션 버튼 */}
            {!readOnly && (
              <div className="ml-auto flex gap-1">
                <Button type="button" size="sm" variant="outline" className="h-7 text-xs" onClick={() => handleMoveUp(index)} disabled={index === 0}>
                  <ArrowUp className="h-3 w-3" />
                </Button>
                <Button type="button" size="sm" variant="outline" className="h-7 text-xs" onClick={() => handleMoveDown(index)} disabled={index === components.length - 1}>
                  <ArrowDown className="h-3 w-3" />
                </Button>
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  className="h-7 text-xs text-green-700"
                  onClick={() => {
                    if (!comp.sourceItemId) {
                      toast.error('연결된 기초자료가 없습니다.');
                      return;
                    }
                    router.push(`/production/bending/${comp.sourceItemId}?mode=edit`);
                  }}
                >
                  <Edit className="h-3 w-3 mr-0.5" />원본수정
                </Button>
                <Button type="button" size="sm" variant="outline" className="h-7 text-xs text-blue-700" onClick={() => handleOpenSaveAs(index)}>
                  <Copy className="h-3 w-3 mr-0.5" />다른이름저장
                </Button>
                <Button type="button" size="sm" variant="destructive" className="h-7 text-xs" onClick={() => handleRemove(index)}>
                  <Trash2 className="h-3 w-3 mr-0.5" />삭제
                </Button>
              </div>
            )}
          </div>

          {/* 부품 이미지 썸네일 */}
          {comp.imageUrl && (
            <TooltipProvider delayDuration={200}>
              <Tooltip>
                <TooltipTrigger asChild>
                  <div className="w-[80px] h-[60px] border rounded overflow-hidden cursor-pointer">
                    <img src={comp.imageUrl} alt={comp.itemName} className="w-full h-full object-contain" />
                  </div>
                </TooltipTrigger>
                <TooltipContent side="right" className="p-1 max-w-none">
                  <img src={comp.imageUrl} alt={comp.itemName} className="w-52 h-52 object-contain" />
                </TooltipContent>
              </Tooltip>
            </TooltipProvider>
          )}

          {/* 부품별 절곡 테이블 */}
          <BendingTable
            data={comp.bendingData}
            onChange={(data) => handleBendingDataChange(index, data)}
            readOnly={readOnly}
            showActions={false}
            showSummary={false}
          />
        </div>
      ))}

      {/* 빈 상태 */}
      {components.length === 0 && (
        <div className="border-2 border-dashed rounded-lg p-8 text-center text-muted-foreground">
          <p className="mb-2">등록된 부품이 없습니다.</p>
          {!readOnly && (
            <Button variant="outline" onClick={onAddParts}>
              <Plus className="h-4 w-4 mr-1" />부품 추가
            </Button>
          )}
        </div>
      )}

      {/* 재질별 폭합 */}
      {components.length > 0 && <MaterialSummary components={components} />}

      {/* 다른이름저장 다이얼로그 */}
      <Dialog open={saveAsOpen} onOpenChange={setSaveAsOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>다른이름으로 기초자료 저장</DialogTitle>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <div className="space-y-1">
              <Label className="text-sm">품명 (새 이름)</Label>
              <Input
                value={saveAsName}
                onChange={(e) => setSaveAsName(e.target.value)}
                placeholder="새 품명을 입력하세요"
                autoFocus
              />
            </div>
            <p className="text-xs text-muted-foreground">
              원본 기초자료 데이터를 가져와 새 이름으로 등록 화면으로 이동합니다.
            </p>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setSaveAsOpen(false)}>취소</Button>
            <Button onClick={handleSaveAs} disabled={!saveAsName.trim()}>
              <Copy className="w-4 h-4 mr-1" />
              이동
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
