/**
 * 발주 개소 목록 패널
 *
 * - 개소 목록 테이블
 * - 품목 추가 폼
 * - 엑셀 업로드/다운로드
 */

"use client";

import { useState, useCallback } from "react";
import { Plus, Upload, Download, Pencil, Trash2, Copy } from "lucide-react";
import { toast } from "sonner";

import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { NumberInput } from "../ui/number-input";
import { QuantityInput } from "../ui/quantity-input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "../ui/select";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "../ui/table";
import { DeleteConfirmDialog } from "../ui/confirm-dialog";

import type { LocationItem } from "./QuoteRegistration";
import type { FinishedGoods } from "./actions";
// xlsx는 동적 로드 (번들 크기 최적화)

// =============================================================================
// 상수
// =============================================================================

// 층 옵션 (지하3층 ~ 지상10층)
const FLOOR_OPTIONS = [
  "B3", "B2", "B1",
  "1F", "2F", "3F", "4F", "5F", "6F", "7F", "8F", "9F", "10F",
  "R",
];

// 가이드레일 설치 유형
const GUIDE_RAIL_TYPES = [
  { value: "wall", label: "벽면형" },
  { value: "floor", label: "측면형" },
  { value: "mixed", label: "혼합형" },
];

// 제품 specification에서 가이드레일 타입 추출
function getGuideRailFromSpec(spec?: string, itemName?: string): string | null {
  const text = spec || itemName || '';
  if (text.includes('혼합')) return 'mixed';
  if (text.includes('벽면')) return 'wall';
  if (text.includes('측면')) return 'floor';
  return null;
}

// 모터 전원
const MOTOR_POWERS = [
  { value: "single", label: "단상(220V)" },
  { value: "three", label: "삼상(380V)" },
];

// 제어기 설치 방식
const CONTROLLERS = [
  { value: "exposed", label: "노출형" },
  { value: "embedded", label: "매립형(뒷박스 포함)" },
  { value: "embedded_no_box", label: "매립형(뒷박스 제외)" },
];

// =============================================================================
// Props
// =============================================================================

interface LocationListPanelProps {
  locations: LocationItem[];
  selectedLocationId: string | null;
  onSelectLocation: (id: string) => void;
  onAddLocation: (location: Omit<LocationItem, "id">) => Promise<boolean>;
  onDeleteLocation: (id: string) => void;
  onCloneLocation?: (id: string) => void;
  onUpdateLocation: (locationId: string, updates: Partial<LocationItem>) => void;
  onExcelUpload: (locations: Omit<LocationItem, "id">[]) => void;
  finishedGoods: FinishedGoods[];
  locationCodes?: string[];
  disabled?: boolean;
}

// =============================================================================
// 컴포넌트
// =============================================================================

export function LocationListPanel({
  locations,
  selectedLocationId,
  onSelectLocation,
  onAddLocation,
  onDeleteLocation,
  onCloneLocation,
  onUpdateLocation: _onUpdateLocation,
  onExcelUpload,
  finishedGoods,
  locationCodes = [],
  disabled = false,
}: LocationListPanelProps) {
  // ---------------------------------------------------------------------------
  // 상태
  // ---------------------------------------------------------------------------

  // 추가 폼 상태
  const [formData, setFormData] = useState({
    floor: "",
    code: "",
    openWidth: "",
    openHeight: "",
    productCode: "",
    quantity: "1",
    guideRailType: "wall",
    motorPower: "single",
    controller: "exposed",
  });

  // 삭제 확인 다이얼로그
  const [deleteTarget, setDeleteTarget] = useState<string | null>(null);

  // ---------------------------------------------------------------------------
  // 핸들러
  // ---------------------------------------------------------------------------

  // 폼 필드 변경
  const handleFormChange = useCallback((field: string, value: string) => {
    setFormData((prev) => ({ ...prev, [field]: value }));
  }, []);

  // 개소 추가 (BOM 계산 성공 시에만 폼 초기화)
  const handleAdd = useCallback(async () => {
    // 유효성 검사
    if (!formData.openWidth || !formData.openHeight) {
      toast.error("가로와 세로를 입력해주세요.");
      return;
    }
    if (!formData.productCode) {
      toast.error("제품을 선택해주세요.");
      return;
    }

    const product = finishedGoods.find((fg) => fg.item_code === formData.productCode);

    // 층/부호 자동 채움: 비어있으면 마지막 개소 기준으로 복제 스타일 적용
    let autoFloor = formData.floor || "-";
    let autoCode = formData.code || "-";
    if (locations.length > 0 && !formData.floor && !formData.code) {
      const lastLoc = locations[locations.length - 1];
      autoFloor = lastLoc.floor || "-";
      // 부호 +1: 접두어 + 숫자 패턴 분석
      const codeMatch = lastLoc.code.match(/^(.*?)(\d+)$/);
      if (codeMatch) {
        const prefix = codeMatch[1];
        const numLength = codeMatch[2].length;
        let maxNum = 0;
        locations.forEach((loc) => {
          const m = loc.code.match(new RegExp(`^${prefix.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(\\d+)$`));
          if (m) maxNum = Math.max(maxNum, parseInt(m[1], 10));
        });
        autoCode = prefix + String(maxNum + 1).padStart(numLength, "0");
      } else {
        autoCode = lastLoc.code || "-";
      }
    }

    const newLocation: Omit<LocationItem, "id"> = {
      floor: autoFloor,
      code: autoCode,
      openWidth: parseFloat(formData.openWidth) || 0,
      openHeight: parseFloat(formData.openHeight) || 0,
      productCode: formData.productCode,
      productName: product?.item_name || formData.productCode,
      itemCategory: product?.item_category,
      quantity: parseInt(formData.quantity) || 1,
      guideRailType: formData.guideRailType,
      motorPower: formData.motorPower,
      controller: formData.controller,
      wingSize: 50,
      inspectionFee: 50000,
    };

    // BOM 계산 성공 시에만 폼 초기화
    const success = await onAddLocation(newLocation);

    if (success) {
      // 폼 초기화 (층/부호만 초기화, 나머지 설정값 유지)
      setFormData((prev) => ({
        ...prev,
        floor: "",
        code: "",
      }));
    }
  }, [formData, finishedGoods, onAddLocation]);

  // 엑셀 양식 다운로드
  const handleDownloadTemplate = useCallback(async () => {
    const XLSX = await import("xlsx");
    const templateData = [
      {
        층: "1층",
        부호: "FSS-01",
        가로: 5000,
        세로: 3000,
        제품코드: "KSS01",
        수량: 1,
        가이드레일: "wall",
        전원: "single",
        제어기: "exposed",
      },
    ];

    const ws = XLSX.utils.json_to_sheet(templateData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "개소목록");

    // 컬럼 너비 설정
    ws["!cols"] = [
      { wch: 10 }, // 층
      { wch: 12 }, // 부호
      { wch: 10 }, // 가로
      { wch: 10 }, // 세로
      { wch: 15 }, // 제품코드
      { wch: 8 }, // 수량
      { wch: 12 }, // 가이드레일
      { wch: 12 }, // 전원
      { wch: 12 }, // 제어기
    ];

    XLSX.writeFile(wb, "견적_개소목록_양식.xlsx");
    toast.success("엑셀 양식이 다운로드되었습니다.");
  }, []);

  // 엑셀 업로드
  const handleFileUpload = useCallback(
    async (event: React.ChangeEvent<HTMLInputElement>) => {
      const file = event.target.files?.[0];
      if (!file) return;

      const XLSX = await import("xlsx");
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const data = new Uint8Array(e.target?.result as ArrayBuffer);
          const workbook = XLSX.read(data, { type: "array" });
          const sheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(worksheet);

          const parsedLocations: Omit<LocationItem, "id">[] = jsonData.map((row: any) => {
            const productCode = row["제품코드"] || "";
            const product = finishedGoods.find((fg) => fg.item_code === productCode);

            return {
              floor: String(row["층"] || ""),
              code: String(row["부호"] || ""),
              openWidth: parseFloat(row["가로"]) || 0,
              openHeight: parseFloat(row["세로"]) || 0,
              productCode: productCode,
              productName: product?.item_name || productCode,
              quantity: parseInt(row["수량"]) || 1,
              guideRailType: row["가이드레일"] || "wall",
              motorPower: row["전원"] || "single",
              controller: row["제어기"] || "exposed",
              wingSize: 50,
              inspectionFee: 50000,
            };
          });

          // 유효한 데이터만 필터링
          const validLocations = parsedLocations.filter(
            (loc) => loc.floor && loc.code && loc.openWidth > 0 && loc.openHeight > 0
          );

          if (validLocations.length === 0) {
            toast.error("유효한 데이터가 없습니다. 양식을 확인해주세요.");
            return;
          }

          onExcelUpload(validLocations);
        } catch (error) {
          console.error("엑셀 파싱 오류:", error);
          toast.error("엑셀 파일을 읽는 중 오류가 발생했습니다.");
        }
      };
      reader.readAsArrayBuffer(file);

      // 파일 입력 초기화
      event.target.value = "";
    },
    [finishedGoods, onExcelUpload]
  );

  // ---------------------------------------------------------------------------
  // 렌더링
  // ---------------------------------------------------------------------------

  return (
    <div className="border-r border-gray-200 flex flex-col">
      {/* ① 입력 영역 (상단으로 이동) */}
      {!disabled && (
        <div className="bg-gray-100 p-4 space-y-3 border-b border-gray-200 min-h-[128px]">
          {/* 1행: 층, 부호, 가로, 세로, 제품코드, 수량 */}
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2">
            <div>
              <label className="text-xs text-gray-600">층</label>
              <Input
                list="floorOptionList"
                placeholder="예: 1F"
                value={formData.floor}
                onChange={(e) => handleFormChange("floor", e.target.value)}
                className="h-8 text-sm border border-gray-300 placeholder:text-gray-400"
              />
              <datalist id="floorOptionList">
                {FLOOR_OPTIONS.map((f) => (
                  <option key={f} value={f} />
                ))}
              </datalist>
            </div>
            <div>
              <label className="text-xs text-gray-600">부호</label>
              <Input
                list="locationCodeList"
                placeholder="예: FSS-01"
                value={formData.code}
                onChange={(e) => handleFormChange("code", e.target.value)}
                className="h-8 text-sm border border-gray-300 placeholder:text-gray-400"
              />
              <datalist id="locationCodeList">
                {locationCodes.map((code) => (
                  <option key={code} value={code} />
                ))}
              </datalist>
            </div>
            <div>
              <label className="text-xs text-gray-600">가로</label>
              <NumberInput
                placeholder="예: 5000"
                value={formData.openWidth ? Number(formData.openWidth) : undefined}
                onChange={(value) => handleFormChange("openWidth", value?.toString() ?? "")}
                className="h-8 text-sm border border-gray-300 placeholder:text-gray-400"
              />
            </div>
            <div>
              <label className="text-xs text-gray-600">세로</label>
              <NumberInput
                placeholder="예: 3000"
                value={formData.openHeight ? Number(formData.openHeight) : undefined}
                onChange={(value) => handleFormChange("openHeight", value?.toString() ?? "")}
                className="h-8 text-sm border border-gray-300 placeholder:text-gray-400"
              />
            </div>
            <div>
              <label className="text-xs text-gray-600">제품코드</label>
              <Select
                value={formData.productCode}
                onValueChange={(value) => {
                  handleFormChange("productCode", value);
                  const product = finishedGoods.find((fg) => fg.item_code === value);
                  const guideRail = product ? getGuideRailFromSpec(product.specification, product.item_name) : null;
                  if (guideRail) {
                    handleFormChange("guideRailType", guideRail);
                  }
                }}
              >
                <SelectTrigger className="h-8 text-sm border border-gray-300">
                  <SelectValue placeholder="선택" />
                </SelectTrigger>
                <SelectContent>
                  {(() => {
                    const existingCode = locations.length > 0 ? locations[0].productCode : null;
                    const existingModel = existingCode?.split('-')[1] ?? null;
                    const filtered = existingModel
                      ? finishedGoods.filter((fg) => fg.item_code.split('-')[1] === existingModel)
                      : finishedGoods;
                    return filtered.map((fg) => (
                      <SelectItem key={fg.item_code} value={fg.item_code}>
                        {fg.item_code}
                      </SelectItem>
                    ));
                  })()}
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-xs text-gray-600">수량</label>
              <QuantityInput
                value={formData.quantity ? Number(formData.quantity) : undefined}
                onChange={(value) => handleFormChange("quantity", value?.toString() ?? "")}
                className="h-8 text-sm border border-gray-300"
                min={1}
              />
            </div>
          </div>

          {/* 2행: 가이드레일, 전원, 제어기, + 버튼 */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
            <div>
              <label className="text-xs text-gray-600 flex items-center gap-1">
                🔧 가이드레일
                <span className="text-[10px] text-gray-400">(제품코드 연동)</span>
              </label>
              <Select
                value={formData.guideRailType}
                onValueChange={(value) => handleFormChange("guideRailType", value)}
                disabled
              >
                <SelectTrigger className="h-8 text-sm border border-gray-300">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {GUIDE_RAIL_TYPES.map((type) => (
                    <SelectItem key={type.value} value={type.value}>
                      {type.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex-1">
              <label className="text-xs text-gray-600 flex items-center gap-1">
                ⚡ 전원
              </label>
              <Select
                value={formData.motorPower}
                onValueChange={(value) => handleFormChange("motorPower", value)}
              >
                <SelectTrigger className="h-8 text-sm border border-gray-300">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {MOTOR_POWERS.map((power) => (
                    <SelectItem key={power.value} value={power.value}>
                      {power.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex-1">
              <label className="text-xs text-gray-600 flex items-center gap-1">
                📦 제어기
              </label>
              <Select
                value={formData.controller}
                onValueChange={(value) => handleFormChange("controller", value)}
              >
                <SelectTrigger className="h-8 text-sm border border-gray-300">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {CONTROLLERS.map((ctrl) => (
                    <SelectItem key={ctrl.value} value={ctrl.value}>
                      {ctrl.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex items-end">
              <Button
                onClick={handleAdd}
                className="w-full h-[36px] bg-green-500 hover:bg-green-600"
              >
                <Plus className="h-4 w-4" />
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* 발주 개소 목록 헤더 */}
      <div className="bg-gray-50 px-4 py-3 border-b border-gray-200">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">
          <h3 className="font-semibold text-gray-700">
            발주 개소 목록 ({locations.length})
          </h3>
          <div className="flex gap-1">
            <Button
              variant="outline"
              size="sm"
              onClick={handleDownloadTemplate}
              disabled={disabled}
              className="text-xs"
            >
              <Download className="h-3 w-3 mr-1" />
              양식
            </Button>
            <label>
              <input
                type="file"
                accept=".xlsx,.xls"
                onChange={handleFileUpload}
                disabled={disabled}
                className="hidden"
              />
              <Button
                variant="outline"
                size="sm"
                disabled={disabled}
                className="text-xs"
                asChild
              >
                <span>
                  <Upload className="h-3 w-3 mr-1" />
                  업로드
                </span>
              </Button>
            </label>
          </div>
        </div>
      </div>

      {/* 개소 목록 테이블 */}
      <div className="flex-1 overflow-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="text-center">층</TableHead>
              <TableHead className="text-center">부호</TableHead>
              <TableHead className="text-center">사이즈</TableHead>
              <TableHead className="text-center">제품</TableHead>
              <TableHead className="text-center">수량</TableHead>
              {!disabled && <TableHead className="w-[80px] text-center"></TableHead>}
            </TableRow>
          </TableHeader>
          <TableBody>
            {locations.length === 0 ? (
              <TableRow>
                <TableCell colSpan={disabled ? 5 : 6} className="text-center text-gray-500 py-8">
                  개소를 추가해주세요
                </TableCell>
              </TableRow>
            ) : (
              locations.map((loc) => (
                <TableRow
                  key={loc.id}
                  className={`cursor-pointer hover:bg-blue-50 ${
                    selectedLocationId === loc.id ? "bg-gray-100 border-l-4 border-l-gray-800" : ""
                  }`}
                  onClick={() => onSelectLocation(loc.id)}
                >
                  <TableCell className="text-center">{loc.floor}</TableCell>
                  <TableCell className="text-center font-medium">{loc.code}</TableCell>
                  <TableCell className="text-center">{loc.openWidth}X{loc.openHeight}</TableCell>
                  <TableCell className="text-center">{loc.productCode}</TableCell>
                  <TableCell className="text-center">{loc.quantity}</TableCell>
                  {!disabled && (
                    <TableCell className="text-center">
                      <div className="flex items-center justify-center gap-1">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onSelectLocation(loc.id);
                          }}
                          className="p-1 hover:bg-gray-200 rounded"
                          title="수정"
                        >
                          <Pencil className="h-4 w-4 text-gray-600" />
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            onCloneLocation?.(loc.id);
                          }}
                          className="p-1 hover:bg-blue-100 rounded"
                          title="복제"
                        >
                          <Copy className="h-4 w-4 text-blue-500" />
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setDeleteTarget(loc.id);
                          }}
                          className="p-1 hover:bg-red-100 rounded"
                          title="삭제"
                        >
                          <Trash2 className="h-4 w-4 text-red-500" />
                        </button>
                      </div>
                    </TableCell>
                  )}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* 삭제 확인 다이얼로그 */}
      <DeleteConfirmDialog
        open={!!deleteTarget}
        onOpenChange={() => setDeleteTarget(null)}
        onConfirm={() => {
          if (deleteTarget) {
            onDeleteLocation(deleteTarget);
            setDeleteTarget(null);
          }
        }}
        title="개소 삭제"
        description="선택한 개소를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다."
      />
    </div>
  );
}