"use client";

import React, { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Plus, Trash2, RotateCcw, Save, Search, Loader2, FileSpreadsheet, Download,
  Package, Pencil, Copy,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { apiClient } from "@/lib/api/client";
import { ExcelUploadModal } from "@/components/common/ExcelUploadModal";
import { exportToExcel } from "@/lib/utils/excelExport";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";

// 테이블 컬럼 정의
const TABLE_COLUMNS = [
  { key: "item_number", label: "품목코드", width: "w-[120px]" },
  { key: "item_name", label: "품명", width: "min-w-[150px]" },
  { key: "division", label: "관리품목", width: "w-[100px]" },
  { key: "type", label: "품목구분", width: "w-[100px]" },
  { key: "size", label: "규격", width: "w-[100px]" },
  { key: "unit", label: "단위", width: "w-[80px]" },
  { key: "material", label: "재질", width: "w-[100px]" },
  { key: "status", label: "상태", width: "w-[80px]" },
  { key: "selling_price", label: "판매가격", width: "w-[100px]" },
  { key: "standard_price", label: "기준단가", width: "w-[100px]" },
  { key: "weight", label: "중량", width: "w-[80px]" },
  { key: "inventory_unit", label: "재고단위", width: "w-[80px]" },
  { key: "user_type01", label: "대분류", width: "w-[100px]" },
  { key: "user_type02", label: "중분류", width: "w-[100px]" },
];

// 등록 모달 필드 정의
const FORM_FIELDS = [
  { key: "item_number", label: "품목코드", type: "text", required: true, disabled: true, placeholder: "자동 채번" },
  { key: "item_name", label: "품명", type: "text", required: true },
  { key: "division", label: "관리품목", type: "category" },
  { key: "type", label: "품목구분", type: "category" },
  { key: "size", label: "규격", type: "text" },
  { key: "unit", label: "단위", type: "category" },
  { key: "material", label: "재질", type: "category" },
  { key: "status", label: "상태", type: "category" },
  { key: "weight", label: "중량", type: "text", placeholder: "숫자 입력 (예: 3.5)" },
  { key: "volum", label: "부피", type: "text", placeholder: "숫자 입력 (예: 100)" },
  { key: "specific_gravity", label: "비중", type: "text", placeholder: "숫자 입력 (예: 7.85)" },
  { key: "inventory_unit", label: "재고단위", type: "category" },
  { key: "selling_price", label: "판매가격", type: "text" },
  { key: "standard_price", label: "기준단가", type: "text" },
  { key: "currency_code", label: "통화", type: "category" },
  { key: "user_type01", label: "대분류", type: "category" },
  { key: "user_type02", label: "중분류", type: "category" },
  { key: "meno", label: "메모", type: "textarea" },
];

const TABLE_NAME = "item_info";

export default function ItemInfoPage() {
  const { user } = useAuth();
  const [items, setItems] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [totalCount, setTotalCount] = useState(0);

  // 검색
  const [searchKeyword, setSearchKeyword] = useState("");
  const [searchDivision, setSearchDivision] = useState("all");
  const [searchType, setSearchType] = useState("all");
  const [searchStatus, setSearchStatus] = useState("all");

  // 모달
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [editId, setEditId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [formData, setFormData] = useState<Record<string, any>>({});

  // 엑셀 업로드
  const [excelUploadOpen, setExcelUploadOpen] = useState(false);

  // 카테고리 옵션 (API에서 로드)
  const [categoryOptions, setCategoryOptions] = useState<Record<string, { code: string; label: string }[]>>({});

  // 선택된 행
  const [selectedId, setSelectedId] = useState<string | null>(null);

  // 카테고리 컬럼 목록
  const CATEGORY_COLUMNS = ["division", "type", "unit", "material", "status", "inventory_unit", "currency_code", "user_type01", "user_type02"];

  // 카테고리 옵션 로드 (table_name + column_name 기반)
  useEffect(() => {
    const loadCategories = async () => {
      try {
        const optMap: Record<string, { code: string; label: string }[]> = {};
        const flatten = (vals: any[]): { code: string; label: string }[] => {
          const result: { code: string; label: string }[] = [];
          for (const v of vals) {
            result.push({ code: v.valueCode, label: v.valueLabel });
            if (v.children?.length) result.push(...flatten(v.children));
          }
          return result;
        };

        await Promise.all(
          CATEGORY_COLUMNS.map(async (colName) => {
            try {
              const res = await apiClient.get(`/table-categories/${TABLE_NAME}/${colName}/values`);
              if (res.data?.success && res.data.data?.length > 0) {
                optMap[colName] = flatten(res.data.data);
              }
            } catch { /* skip */ }
          })
        );
        setCategoryOptions(optMap);
      } catch (err) {
        console.error("카테고리 로드 실패:", err);
      }
    };
    loadCategories();
  }, []);

  // 데이터 조회
  const fetchItems = useCallback(async () => {
    setLoading(true);
    try {
      const filters: any[] = [];
      if (searchKeyword) {
        filters.push({ columnName: "item_name", operator: "contains", value: searchKeyword });
      }
      if (searchDivision !== "all") {
        filters.push({ columnName: "division", operator: "equals", value: searchDivision });
      }
      if (searchType !== "all") {
        filters.push({ columnName: "type", operator: "equals", value: searchType });
      }
      if (searchStatus !== "all") {
        filters.push({ columnName: "status", operator: "equals", value: searchStatus });
      }

      const res = await apiClient.post(`/table-management/tables/${TABLE_NAME}/data`, {
        page: 1,
        size: 500,
        dataFilter: filters.length > 0 ? { enabled: true, filters } : undefined,
        autoFilter: true,
      });

      const raw = res.data?.data?.data || res.data?.data?.rows || [];
      // 카테고리 코드→라벨 변환
      const resolve = (col: string, code: string) => {
        if (!code) return "";
        return categoryOptions[col]?.find((o) => o.code === code)?.label || code;
      };
      const data = raw.map((r: any) => {
        const converted = { ...r };
        for (const col of CATEGORY_COLUMNS) {
          if (converted[col]) converted[col] = resolve(col, converted[col]);
        }
        return converted;
      });
      setItems(data);
      setTotalCount(res.data?.data?.total || raw.length);
    } catch (err) {
      console.error("품목 조회 실패:", err);
      toast.error("품목 목록을 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  }, [searchKeyword, searchDivision, searchType, searchStatus, categoryOptions]);

  useEffect(() => {
    fetchItems();
  }, [fetchItems]);

  // 카테고리 코드 → 라벨 변환
  const getCategoryLabel = (columnName: string, code: string) => {
    if (!code) return "";
    const opts = categoryOptions[columnName];
    if (!opts) return code;
    const found = opts.find((o) => o.code === code);
    return found?.label || code;
  };

  // 등록 모달 열기
  const openRegisterModal = () => {
    setFormData({});
    setIsEditMode(false);
    setEditId(null);
    setIsModalOpen(true);
  };

  // 수정 모달 열기
  const openEditModal = (item: any) => {
    setFormData({ ...item });
    setIsEditMode(true);
    setEditId(item.id);
    setIsModalOpen(true);
  };

  // 복사 모달 열기
  const openCopyModal = (item: any) => {
    const { id, item_number, created_date, updated_date, writer, ...rest } = item;
    setFormData(rest);
    setIsEditMode(false);
    setEditId(null);
    setIsModalOpen(true);
  };

  // 저장
  const handleSave = async () => {
    if (!formData.item_name) {
      toast.error("품명은 필수 입력입니다.");
      return;
    }

    setSaving(true);
    try {
      if (isEditMode && editId) {
        // 수정
        const { id, created_date, updated_date, writer, company_code, ...updateFields } = formData;
        await apiClient.put(`/table-management/tables/${TABLE_NAME}/edit`, {
          originalData: { id: editId },
          updatedData: updateFields,
        });
        toast.success("수정되었습니다.");
      } else {
        // 등록
        const { id, created_date, updated_date, ...insertFields } = formData;
        await apiClient.post(`/table-management/tables/${TABLE_NAME}/add`, insertFields);
        toast.success("등록되었습니다.");
      }
      setIsModalOpen(false);
      fetchItems();
    } catch (err: any) {
      console.error("저장 실패:", err);
      toast.error(err.response?.data?.message || "저장에 실패했습니다.");
    } finally {
      setSaving(false);
    }
  };

  // 삭제
  const handleDelete = async () => {
    if (!selectedId) {
      toast.error("삭제할 품목을 선택해주세요.");
      return;
    }
    if (!confirm("선택한 품목을 삭제하시겠습니까?")) return;

    try {
      await apiClient.delete(`/table-management/tables/${TABLE_NAME}/delete`, {
        data: [{ id: selectedId }],
      });
      toast.success("삭제되었습니다.");
      setSelectedId(null);
      fetchItems();
    } catch (err) {
      console.error("삭제 실패:", err);
      toast.error("삭제에 실패했습니다.");
    }
  };

  // 엑셀 다운로드
  const handleExcelDownload = async () => {
    if (items.length === 0) {
      toast.error("다운로드할 데이터가 없습니다.");
      return;
    }
    const exportData = items.map((item) => {
      const row: Record<string, any> = {};
      for (const col of TABLE_COLUMNS) {
        row[col.label] = getCategoryLabel(col.key, item[col.key]) || item[col.key] || "";
      }
      return row;
    });
    await exportToExcel(exportData, "품목정보.xlsx", "품목정보");
    toast.success("엑셀 다운로드 완료");
  };

  // 검색 초기화
  const handleResetSearch = () => {
    setSearchKeyword("");
    setSearchDivision("all");
    setSearchType("all");
    setSearchStatus("all");
  };

  // 카테고리 셀렉트 렌더링
  const renderCategorySelect = (field: typeof FORM_FIELDS[0]) => {
    const options = categoryOptions[field.key] || [];
    return (
      <Select
        value={formData[field.key] || ""}
        onValueChange={(v) => setFormData((prev) => ({ ...prev, [field.key]: v }))}
      >
        <SelectTrigger className="h-9 text-sm">
          <SelectValue placeholder={`${field.label} 선택`} />
        </SelectTrigger>
        <SelectContent>
          {options.map((opt) => (
            <SelectItem key={opt.code} value={opt.code}>
              {opt.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    );
  };

  return (
    <div className="flex h-full flex-col gap-3 p-3">
      {/* 검색 */}
      <Card className="shrink-0">
        <CardContent className="p-4 flex flex-wrap items-end gap-4">
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">품명/품목코드</Label>
            <Input
              placeholder="검색"
              className="w-[180px] h-9"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && fetchItems()}
            />
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">관리품목</Label>
            <Select value={searchDivision} onValueChange={setSearchDivision}>
              <SelectTrigger className="w-[120px] h-9"><SelectValue placeholder="전체" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체</SelectItem>
                {(categoryOptions["division"] || []).map((o) => (
                  <SelectItem key={o.code} value={o.code}>{o.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">품목구분</Label>
            <Select value={searchType} onValueChange={setSearchType}>
              <SelectTrigger className="w-[120px] h-9"><SelectValue placeholder="전체" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체</SelectItem>
                {(categoryOptions["type"] || []).map((o) => (
                  <SelectItem key={o.code} value={o.code}>{o.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="space-y-1.5">
            <Label className="text-xs text-muted-foreground">상태</Label>
            <Select value={searchStatus} onValueChange={setSearchStatus}>
              <SelectTrigger className="w-[110px] h-9"><SelectValue placeholder="전체" /></SelectTrigger>
              <SelectContent>
                <SelectItem value="all">전체</SelectItem>
                {(categoryOptions["status"] || []).map((o) => (
                  <SelectItem key={o.code} value={o.code}>{o.label}</SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <div className="flex-1" />
          <div className="flex items-center gap-2">
            {loading && <Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />}
            <Button variant="outline" size="sm" className="h-9" onClick={handleResetSearch}>
              <RotateCcw className="w-4 h-4 mr-2" /> 초기화
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 메인 테이블 */}
      <div className="flex-1 overflow-hidden border rounded-lg bg-background shadow-sm flex flex-col">
        <div className="flex items-center justify-between p-3 border-b bg-muted/10 shrink-0">
          <div className="font-semibold flex items-center gap-2 text-sm">
            <Package className="w-5 h-5" /> 품목 목록
            <Badge variant="secondary" className="font-normal">{totalCount}건</Badge>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => setExcelUploadOpen(true)}>
              <FileSpreadsheet className="w-4 h-4 mr-1.5" /> 엑셀 업로드
            </Button>
            <Button variant="outline" size="sm" onClick={handleExcelDownload}>
              <Download className="w-4 h-4 mr-1.5" /> 엑셀 다운로드
            </Button>
            <Button size="sm" onClick={openRegisterModal}>
              <Plus className="w-4 h-4 mr-1.5" /> 품목 등록
            </Button>
            <Button variant="outline" size="sm" disabled={!selectedId} onClick={() => {
              const item = items.find((i) => i.id === selectedId);
              if (item) openCopyModal(item);
            }}>
              <Copy className="w-4 h-4 mr-1.5" /> 복사
            </Button>
            <Button variant="outline" size="sm" disabled={!selectedId} onClick={() => {
              const item = items.find((i) => i.id === selectedId);
              if (item) openEditModal(item);
            }}>
              <Pencil className="w-4 h-4 mr-1.5" /> 수정
            </Button>
            <Button variant="destructive" size="sm" disabled={!selectedId} onClick={handleDelete}>
              <Trash2 className="w-4 h-4 mr-1.5" /> 삭제
            </Button>
          </div>
        </div>

        <div className="flex-1 overflow-auto">
          {loading ? (
            <div className="flex items-center justify-center h-32">
              <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
            </div>
          ) : items.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-32 text-muted-foreground gap-2">
              <Package className="w-8 h-8 opacity-50" />
              <span>등록된 품목이 없습니다</span>
            </div>
          ) : (
            <Table>
              <TableHeader className="sticky top-0 bg-background z-10 shadow-sm">
                <TableRow>
                  <TableHead className="w-[40px] text-center">No</TableHead>
                  {TABLE_COLUMNS.map((col) => (
                    <TableHead key={col.key} className={col.width}>{col.label}</TableHead>
                  ))}
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((item, idx) => (
                  <TableRow
                    key={item.id}
                    className={cn("cursor-pointer", selectedId === item.id && "bg-primary/5")}
                    onClick={() => setSelectedId(item.id)}
                    onDoubleClick={() => openEditModal(item)}
                  >
                    <TableCell className="text-center text-xs text-muted-foreground">{idx + 1}</TableCell>
                    {TABLE_COLUMNS.map((col) => (
                      <TableCell key={col.key} className="text-sm">
                        {["division", "type", "unit", "material", "status", "inventory_unit", "user_type01", "user_type02", "currency_code"].includes(col.key)
                          ? getCategoryLabel(col.key, item[col.key])
                          : item[col.key] || ""}
                      </TableCell>
                    ))}
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </div>
      </div>

      {/* 등록/수정 모달 */}
      <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-auto">
          <DialogHeader>
            <DialogTitle>{isEditMode ? "품목 수정" : "품목 등록"}</DialogTitle>
            <DialogDescription>
              {isEditMode ? "품목 정보를 수정합니다." : "새로운 품목을 등록합니다."}
            </DialogDescription>
          </DialogHeader>

          <div className="grid grid-cols-2 gap-4 py-4">
            {FORM_FIELDS.map((field) => (
              <div key={field.key} className={cn("space-y-1.5", field.type === "textarea" && "col-span-2")}>
                <Label className="text-sm">
                  {field.label}
                  {field.required && <span className="text-destructive ml-1">*</span>}
                </Label>
                {field.type === "category" ? (
                  renderCategorySelect(field)
                ) : field.type === "textarea" ? (
                  <Textarea
                    value={formData[field.key] || ""}
                    onChange={(e) => setFormData((prev) => ({ ...prev, [field.key]: e.target.value }))}
                    placeholder={field.label}
                    rows={3}
                  />
                ) : (
                  <Input
                    value={formData[field.key] || ""}
                    onChange={(e) => setFormData((prev) => ({ ...prev, [field.key]: e.target.value }))}
                    placeholder={field.placeholder || (field.disabled ? "자동 채번" : field.label)}
                    disabled={field.disabled && !isEditMode}
                    className="h-9"
                  />
                )}
              </div>
            ))}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setIsModalOpen(false)}>취소</Button>
            <Button onClick={handleSave} disabled={saving}>
              {saving ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <Save className="w-4 h-4 mr-1.5" />}
              저장
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 엑셀 업로드 모달 */}
      <ExcelUploadModal
        open={excelUploadOpen}
        onOpenChange={setExcelUploadOpen}
        tableName={TABLE_NAME}
        userId={user?.userId}
        onSuccess={() => {
          fetchItems();
        }}
      />
    </div>
  );
}
