"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { Plus } from "lucide-react";
import { toast } from "sonner";
import { createColumnMapping } from "@/lib/api/tableCategoryValue";
import { tableManagementApi } from "@/lib/api/tableManagement";

interface AddCategoryColumnDialogProps {
  tableName: string;
  menuObjid: number;
  menuName: string;
  onSuccess: () => void;
}

/**
 * 카테고리 컬럼 추가 다이얼로그
 * 
 * 논리적 컬럼명과 물리적 컬럼명을 매핑하여 메뉴별로 독립적인 카테고리 관리 가능
 */
export function AddCategoryColumnDialog({
  tableName,
  menuObjid,
  menuName,
  onSuccess,
}: AddCategoryColumnDialogProps) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [physicalColumns, setPhysicalColumns] = useState<string[]>([]);
  const [logicalColumnName, setLogicalColumnName] = useState("");
  const [physicalColumnName, setPhysicalColumnName] = useState("");
  const [description, setDescription] = useState("");

  // 테이블의 실제 컬럼 목록 조회
  useEffect(() => {
    if (open) {
      loadPhysicalColumns();
    }
  }, [open, tableName]);

  const loadPhysicalColumns = async () => {
    try {
      const response = await tableManagementApi.getTableColumns(tableName);
      if (response.success && response.data) {
        setPhysicalColumns(response.data.map((col: any) => col.columnName));
      }
    } catch (error) {
      console.error("컬럼 목록 조회 실패:", error);
      toast.error("컬럼 목록을 불러올 수 없습니다");
    }
  };

  const handleSave = async () => {
    // 입력 검증
    if (!logicalColumnName.trim()) {
      toast.error("논리적 컬럼명을 입력해주세요");
      return;
    }

    if (!physicalColumnName) {
      toast.error("실제 컬럼을 선택해주세요");
      return;
    }

    setLoading(true);

    try {
      const response = await createColumnMapping({
        tableName,
        logicalColumnName: logicalColumnName.trim(),
        physicalColumnName,
        menuObjid,
        description: description.trim() || undefined,
      });

      if (response.success) {
        toast.success("논리적 컬럼이 추가되었습니다");
        setOpen(false);
        resetForm();
        onSuccess();
      } else {
        toast.error(response.error || "컬럼 매핑 생성에 실패했습니다");
      }
    } catch (error: any) {
      console.error("컬럼 매핑 생성 실패:", error);
      toast.error(error.message || "컬럼 매핑 생성 중 오류가 발생했습니다");
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setLogicalColumnName("");
    setPhysicalColumnName("");
    setDescription("");
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          <Plus className="mr-2 h-4 w-4" />
          카테고리 컬럼 추가
        </Button>
      </DialogTrigger>

      <DialogContent className="max-w-[95vw] sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle className="text-base sm:text-lg">
            카테고리 컬럼 추가
          </DialogTitle>
          <DialogDescription className="text-xs sm:text-sm">
            같은 물리적 컬럼을 여러 메뉴에서 다른 카테고리로 사용할 수 있습니다
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3 sm:space-y-4">
          {/* 적용 메뉴 (읽기 전용) */}
          <div>
            <Label className="text-xs sm:text-sm">적용 메뉴</Label>
            <Input
              value={menuName}
              disabled
              className="h-8 text-xs sm:h-10 sm:text-sm"
            />
          </div>

          {/* 실제 컬럼 선택 */}
          <div>
            <Label className="text-xs sm:text-sm">
              실제 컬럼 (물리적) *
            </Label>
            <Select value={physicalColumnName} onValueChange={setPhysicalColumnName}>
              <SelectTrigger className="h-8 text-xs sm:h-10 sm:text-sm">
                <SelectValue placeholder="컬럼 선택" />
              </SelectTrigger>
              <SelectContent>
                {physicalColumns.map((col) => (
                  <SelectItem key={col} value={col} className="text-xs sm:text-sm">
                    {col}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="text-muted-foreground mt-1 text-[10px] sm:text-xs">
              테이블의 실제 컬럼명
            </p>
          </div>

          {/* 논리적 컬럼명 입력 */}
          <div>
            <Label className="text-xs sm:text-sm">
              논리적 컬럼명 (메뉴별 식별용) *
            </Label>
            <Input
              value={logicalColumnName}
              onChange={(e) => setLogicalColumnName(e.target.value)}
              placeholder="예: status_stock, status_sales"
              className="h-8 text-xs sm:h-10 sm:text-sm"
            />
            <p className="text-muted-foreground mt-1 text-[10px] sm:text-xs">
              이 메뉴에서만 사용할 고유한 이름을 입력하세요
            </p>
          </div>

          {/* 설명 (선택사항) */}
          <div>
            <Label className="text-xs sm:text-sm">설명</Label>
            <Textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="이 컬럼의 용도를 설명하세요 (선택사항)"
              className="text-xs sm:text-sm"
              rows={2}
            />
          </div>
        </div>

        <DialogFooter className="gap-2 sm:gap-0">
          <Button
            variant="outline"
            onClick={() => setOpen(false)}
            disabled={loading}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            취소
          </Button>
          <Button
            onClick={handleSave}
            disabled={!logicalColumnName || !physicalColumnName || loading}
            className="h-8 flex-1 text-xs sm:h-10 sm:flex-none sm:text-sm"
          >
            {loading ? "추가 중..." : "추가"}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

