/**
 * BendingDiagramSection - 절곡품/조립품 전개도 섹션
 */

import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { FileDropzone } from '@/components/ui/file-dropzone';
import { NumberInput } from '@/components/ui/number-input';
import { FileImage, Plus, Trash2, X, Download, Loader2 } from 'lucide-react';
import type { BendingDetail } from '@/types/item';
import type { UseFormSetValue } from 'react-hook-form';
import type { CreateItemFormData } from '@/lib/utils/validation';
import { downloadFileById } from '@/lib/utils/fileDownload';
import { toast } from 'sonner';

export interface BendingDiagramSectionProps {
  selectedPartType: string;
  bendingDiagramInputMethod: 'file' | 'drawing';
  setBendingDiagramInputMethod: (method: 'file' | 'drawing') => void;
  bendingDiagram: string;
  setBendingDiagram: (diagram: string) => void;
  setBendingDiagramFile: (file: File | null) => void;
  setIsDrawingOpen: (open: boolean) => void;
  bendingDetails: BendingDetail[];
  setBendingDetails: (details: BendingDetail[]) => void;
  setWidthSum: (sum: string) => void;
  /** 동적 폼에서 폭 합계 필드의 키 (예: 'width_sum', 'field_123') */
  widthSumFieldKey?: string;
  setValue: UseFormSetValue<CreateItemFormData>;
  isSubmitting: boolean;
  /** 기존 전개도 이미지 URL (수정 모드) */
  existingBendingDiagram?: string;
  /** 기존 전개도 파일명 */
  existingBendingDiagramFileName?: string;
  /** 기존 전개도 파일 ID (삭제용) */
  existingBendingDiagramFileId?: number | null;
  /** 기존 파일 삭제 콜백 */
  onDeleteExistingFile?: () => void;
  /** 파일 삭제 중 상태 */
  isDeletingFile?: boolean;
}

export default function BendingDiagramSection({
  selectedPartType,
  bendingDiagramInputMethod,
  setBendingDiagramInputMethod,
  bendingDiagram,
  setBendingDiagram,
  setBendingDiagramFile,
  setIsDrawingOpen,
  bendingDetails,
  setBendingDetails,
  setWidthSum,
  widthSumFieldKey,
  setValue,
  isSubmitting,
  existingBendingDiagram: _existingBendingDiagram,
  existingBendingDiagramFileName,
  existingBendingDiagramFileId,
  onDeleteExistingFile,
  isDeletingFile,
}: BendingDiagramSectionProps) {
  // 기존 파일 다운로드 핸들러
  const handleDownloadExistingFile = async () => {
    if (!existingBendingDiagramFileId) {
      toast.error('파일 ID가 없습니다.');
      return;
    }

    try {
      const fileName = existingBendingDiagramFileName || '전개도_이미지';
      await downloadFileById(existingBendingDiagramFileId, fileName);
    } catch (error) {
      console.error('[BendingDiagramSection] 파일 다운로드 실패:', error);
      toast.error('파일 다운로드에 실패했습니다.');
    }
  };
  // 폭 합계 업데이트 헬퍼
  const updateWidthSum = (details: BendingDetail[]) => {
    const totalSum = details.reduce((acc, d) => {
      const calc = d.input + d.elongation;
      return acc + calc;
    }, 0);
    const sumString = totalSum.toString();
    setWidthSum(sumString);

    // 동적 폼 필드에 값 설정 (widthSumFieldKey가 있으면 해당 키로, 없으면 'length'로 폴백)
    if (widthSumFieldKey) {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      setValue(widthSumFieldKey as any, sumString);
    } else {
      setValue('length', sumString);
    }
  };

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <FileImage className="h-5 w-5" />
          {selectedPartType === 'ASSEMBLY' ? '조립품 전개도 (바라시)' : '절곡품 전개도 (바라시)'}
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* 입력방식 선택 */}
        <div>
          <Label>입력방식 선택</Label>
          <div className="mt-2 flex gap-4">
            <div className="flex items-center space-x-2">
              <input
                type="radio"
                id="input-file"
                name="bendingInputMethod"
                value="file"
                checked={bendingDiagramInputMethod === 'file'}
                onChange={(e) => setBendingDiagramInputMethod(e.target.value as 'file')}
                className="h-4 w-4"
              />
              <Label htmlFor="input-file" className="cursor-pointer font-normal">
                파일 선택 (이미지 파일 업로드)
              </Label>
            </div>
            <div className="flex items-center space-x-2">
              <input
                type="radio"
                id="input-drawing"
                name="bendingInputMethod"
                value="drawing"
                checked={bendingDiagramInputMethod === 'drawing'}
                onChange={(e) => setBendingDiagramInputMethod(e.target.value as 'drawing')}
                className="h-4 w-4"
              />
              <Label htmlFor="input-drawing" className="cursor-pointer font-normal">
                드로잉 (직접 그리기)
              </Label>
            </div>
          </div>
          <p className="text-xs text-muted-foreground mt-1">
            * 전개도 이미지를 파일로 업로드하거나 직접 그릴 수 있습니다
          </p>
        </div>

        {/* 기존 전개도 이미지 (수정 모드) - 파일 ID가 있으면 프록시로 이미지 로드 */}
        {existingBendingDiagramFileId && !bendingDiagram && (
          <div className="p-4 border rounded-lg bg-blue-50 border-blue-200">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <FileImage className="h-5 w-5 text-blue-600" />
                <span className="text-sm font-medium text-blue-900">기존 전개도 이미지</span>
              </div>
              <div className="flex items-center gap-2">
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={handleDownloadExistingFile}
                  className="text-blue-600 border-blue-300 hover:bg-blue-100"
                >
                  <Download className="h-4 w-4 mr-1" />
                  다운로드
                </Button>
                {onDeleteExistingFile && (
                  <Button
                    type="button"
                    variant="outline"
                    size="sm"
                    onClick={onDeleteExistingFile}
                    disabled={isDeletingFile}
                    className="text-red-600 border-red-300 hover:bg-red-50"
                  >
                    {isDeletingFile ? (
                      <>
                        <Loader2 className="h-4 w-4 mr-1 animate-spin" />
                        삭제 중...
                      </>
                    ) : (
                      <>
                        <Trash2 className="h-4 w-4 mr-1" />
                        삭제
                      </>
                    )}
                  </Button>
                )}
              </div>
            </div>
            {existingBendingDiagramFileName && (
              <p className="text-xs text-blue-700 mb-2">
                파일명: {existingBendingDiagramFileName}
              </p>
            )}
            <div className="border rounded bg-white p-2">
              <img
                src={`/api/proxy/files/${existingBendingDiagramFileId}/view`}
                alt="기존 전개도"
                className="max-w-full h-auto max-h-96 mx-auto"
                onError={(e) => {
                  // 이미지 로드 실패 시 대체 텍스트 표시
                  const target = e.target as HTMLImageElement;
                  target.style.display = 'none';
                  target.parentElement?.insertAdjacentHTML(
                    'beforeend',
                    '<p class="text-center text-gray-500 py-8">이미지를 불러올 수 없습니다</p>'
                  );
                }}
              />
            </div>
            <p className="text-xs text-blue-700 mt-2">
              * 새 파일을 업로드하면 기존 파일이 교체됩니다
            </p>
          </div>
        )}

        {/* 파일 선택 방식 */}
        {bendingDiagramInputMethod === 'file' && (
          <div>
            <Label>파일 선택</Label>
            <div className="mt-2 space-y-3">
              <FileDropzone
                onFilesSelect={(files) => {
                  const file = files[0];
                  if (file && typeof window !== 'undefined') {
                    setBendingDiagramFile(file);
                    const reader = new window.FileReader();
                    reader.onloadend = () => {
                      setBendingDiagram(reader.result as string);
                    };
                    reader.readAsDataURL(file);
                  }
                }}
                accept="image/*,.pdf"
                maxSize={10}
                disabled={isSubmitting}
                title="클릭하거나 파일을 드래그하세요"
                description={selectedPartType === 'ASSEMBLY'
                  ? '조립품 전개도 이미지를 업로드하세요(JPG, PNG, PDF 등)'
                  : '절곡품 전개도 이미지를 업로드하세요(JPG, PNG, PDF 등)'}
              />
            </div>

            {/* 전개도 이미지 미리보기 */}
            {bendingDiagram && (
              <div className="mt-4 p-4 border rounded-lg bg-gray-50">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-sm font-medium">미리보기</p>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => {
                      setBendingDiagram('');
                      setBendingDiagramFile(null);
                    }}
                  >
                    <X className="h-4 w-4 mr-1" />
                    전개도 삭제
                  </Button>
                </div>
                <img
                  src={bendingDiagram}
                  alt="전개도 미리보기"
                  className="max-w-full h-auto max-h-96 mx-auto border rounded bg-white"
                />
              </div>
            )}
          </div>
        )}

        {/* 드로잉 방식 */}
        {bendingDiagramInputMethod === 'drawing' && (
          <div>
            <Button
              type="button"
              onClick={() => setIsDrawingOpen(true)}
              className="w-full"
              variant="outline"
            >
              <FileImage className="h-4 w-4 mr-2" />
              {bendingDiagram ? '전개도 수정' : '전개도 그리기'}
            </Button>
            <p className="text-xs text-muted-foreground mt-2">
              * 캔버스에서 직접 전개도를 그릴 수 있습니다
            </p>

            {/* 전개도 미리보기 */}
            {bendingDiagram && (
              <div className="mt-4 p-4 border rounded-lg bg-gray-50">
                <div className="flex items-center justify-between mb-2">
                  <p className="text-sm font-medium">미리보기</p>
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => setBendingDiagram('')}
                  >
                    <X className="h-4 w-4 mr-1" />
                    전개도 삭제
                  </Button>
                </div>
                <img
                  src={bendingDiagram}
                  alt="전개도 미리보기"
                  className="max-w-full h-auto max-h-96 mx-auto border rounded bg-white"
                />
              </div>
            )}
          </div>
        )}

        {/* 전개도 상세 입력 (치수 계산) - BENDING 전용 */}
        {selectedPartType === 'BENDING' && (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <Label>전개도 상세 입력 (치수 계산)</Label>
              <Button
                type="button"
                size="sm"
                variant="outline"
                onClick={() => {
                  const newId = `detail-${Date.now()}`;
                  const newRow: BendingDetail = {
                    id: newId,
                    no: bendingDetails.length + 1,
                    input: 0,
                    elongation: -1,
                    calculated: 0,
                    sum: 0,
                    shaded: false,
                    aAngle: undefined,
                  };
                  setBendingDetails([...bendingDetails, newRow]);
                }}
              >
                <Plus className="h-4 w-4 mr-1" />
                행 추가
              </Button>
            </div>

            {bendingDetails.length > 0 ? (
              <div className="border rounded-lg overflow-hidden">
                <table className="w-full text-sm">
                  <thead className="bg-gray-50 border-b">
                    <tr>
                      <th className="px-3 py-2 text-center w-16">번호</th>
                      <th className="px-3 py-2 text-center">입력값</th>
                      <th className="px-3 py-2 text-center">연신율</th>
                      <th className="px-3 py-2 text-center">계산값</th>
                      <th className="px-3 py-2 text-center w-20">음영</th>
                      <th className="px-3 py-2 text-center">A각</th>
                      <th className="px-3 py-2 text-center w-16">삭제</th>
                    </tr>
                  </thead>
                  <tbody>
                    {bendingDetails.map((detail, index) => {
                      const calculated = detail.input + detail.elongation;

                      return (
                        <tr key={detail.id} className={detail.shaded ? 'bg-gray-100' : ''}>
                          <td className="px-3 py-2 text-center border-b">{detail.no}</td>
                          <td className="px-3 py-2 border-b">
                            <NumberInput
                              value={detail.input}
                              onChange={(value) => {
                                const newDetails = [...bendingDetails];
                                newDetails[index] = {
                                  ...detail,
                                  input: value ?? 0,
                                };
                                setBendingDetails(newDetails);
                                updateWidthSum(newDetails);
                              }}
                              allowDecimal
                              className="h-8 text-center"
                            />
                          </td>
                          <td className="px-3 py-2 border-b">
                            <NumberInput
                              value={detail.elongation}
                              onChange={(value) => {
                                const newDetails = [...bendingDetails];
                                newDetails[index] = {
                                  ...detail,
                                  elongation: value ?? -1,
                                };
                                setBendingDetails(newDetails);
                                updateWidthSum(newDetails);
                              }}
                              allowDecimal
                              className="h-8 text-center"
                            />
                          </td>
                          <td className="px-3 py-2 text-center border-b bg-gray-50">
                            {calculated.toFixed(1)}
                          </td>
                          <td className="px-3 py-2 text-center border-b">
                            <input
                              type="checkbox"
                              checked={detail.shaded}
                              onChange={(e) => {
                                const newDetails = [...bendingDetails];
                                newDetails[index] = {
                                  ...detail,
                                  shaded: e.target.checked,
                                };
                                setBendingDetails(newDetails);
                              }}
                              className="h-4 w-4"
                            />
                          </td>
                          <td className="px-3 py-2 border-b">
                            <NumberInput
                              value={detail.aAngle ?? undefined}
                              onChange={(value) => {
                                const newDetails = [...bendingDetails];
                                newDetails[index] = {
                                  ...detail,
                                  aAngle: value ?? undefined,
                                };
                                setBendingDetails(newDetails);
                              }}
                              allowDecimal
                              className="h-8 text-center"
                              placeholder="각도"
                            />
                          </td>
                          <td className="px-3 py-2 text-center border-b">
                            <Button
                              type="button"
                              size="sm"
                              variant="ghost"
                              onClick={() => {
                                const newDetails = bendingDetails
                                  .filter((_, i) => i !== index)
                                  .map((d, i) => ({ ...d, no: i + 1 }));
                                setBendingDetails(newDetails);
                                updateWidthSum(newDetails);
                              }}
                            >
                              <Trash2 className="h-4 w-4 text-red-500" />
                            </Button>
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                  <tfoot className="bg-gray-50 border-t-2">
                    <tr>
                      <td colSpan={3} className="px-3 py-2 text-right font-semibold">
                        폭 합계:
                      </td>
                      <td className="px-3 py-2 text-center font-bold text-blue-600">
                        {bendingDetails.length > 0
                          ? bendingDetails.reduce((acc, d) => {
                              const calc = d.input + d.elongation;
                              return acc + calc;
                            }, 0).toFixed(1)
                          : '0.0'} mm
                      </td>
                      <td colSpan={3}></td>
                    </tr>
                  </tfoot>
                </table>
              </div>
            ) : (
              <div className="text-center py-8 text-sm text-muted-foreground border rounded-lg bg-gray-50">
                전개도 상세 데이터가 없습니다. "행 추가" 버튼을 클릭하여 추가하세요.
              </div>
            )}

            <p className="text-xs text-muted-foreground">
              * 전개도의 각 구간별 치수를 입력하여 정확한 전개 길이를 계산할 수 있습니다.
            </p>
          </div>
        )}
      </CardContent>
    </Card>
  );
}