"use client";

import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { cn } from "@/lib/utils";
import {
  Loader2, Save, RotateCcw, Plus, Trash2, Pencil, ClipboardCheck,
  ChevronRight, GripVertical, AlertCircle,
} from "lucide-react";
import { toast } from "sonner";
import {
  getWIWorkStandard, copyWorkStandard, saveWIWorkStandard, resetWIWorkStandard,
  WIWorkItem, WIWorkItemDetail, WIWorkStandardProcess,
} from "@/lib/api/workInstruction";

interface WorkStandardEditModalProps {
  open: boolean;
  onClose: () => void;
  workInstructionNo: string;
  routingVersionId: string;
  routingName: string;
  itemName: string;
  itemCode: string;
}

const PHASES = [
  { key: "PRE", label: "사전작업" },
  { key: "MAIN", label: "본작업" },
  { key: "POST", label: "후작업" },
];

const DETAIL_TYPES = [
  { value: "checklist", label: "체크리스트" },
  { value: "inspection", label: "검사항목" },
  { value: "procedure", label: "작업절차" },
  { value: "input", label: "직접입력" },
  { value: "lookup", label: "문서참조" },
  { value: "equip_inspection", label: "설비점검" },
  { value: "equip_condition", label: "설비조건" },
  { value: "production_result", label: "실적등록" },
  { value: "material_input", label: "자재투입" },
];

export function WorkStandardEditModal({
  open,
  onClose,
  workInstructionNo,
  routingVersionId,
  routingName,
  itemName,
  itemCode,
}: WorkStandardEditModalProps) {
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [processes, setProcesses] = useState<WIWorkStandardProcess[]>([]);
  const [isCustom, setIsCustom] = useState(false);
  const [selectedProcessIdx, setSelectedProcessIdx] = useState(0);
  const [selectedPhase, setSelectedPhase] = useState("PRE");
  const [selectedWorkItemId, setSelectedWorkItemId] = useState<string | null>(null);
  const [dirty, setDirty] = useState(false);

  // 작업항목 추가 모달
  const [addItemOpen, setAddItemOpen] = useState(false);
  const [addItemTitle, setAddItemTitle] = useState("");
  const [addItemRequired, setAddItemRequired] = useState("Y");

  // 상세 추가 모달
  const [addDetailOpen, setAddDetailOpen] = useState(false);
  const [addDetailType, setAddDetailType] = useState("checklist");
  const [addDetailContent, setAddDetailContent] = useState("");
  const [addDetailRequired, setAddDetailRequired] = useState("N");

  // 데이터 로드
  const loadData = useCallback(async () => {
    if (!workInstructionNo || !routingVersionId) return;
    setLoading(true);
    try {
      const res = await getWIWorkStandard(workInstructionNo, routingVersionId);
      if (res.success && res.data) {
        setProcesses(res.data.processes);
        setIsCustom(res.data.isCustom);
        setSelectedProcessIdx(0);
        setSelectedPhase("PRE");
        setSelectedWorkItemId(null);
        setDirty(false);
      }
    } catch (err) {
      console.error("공정작업기준 로드 실패", err);
    } finally {
      setLoading(false);
    }
  }, [workInstructionNo, routingVersionId]);

  useEffect(() => {
    if (open) loadData();
  }, [open, loadData]);

  const currentProcess = processes[selectedProcessIdx] || null;
  const currentWorkItems = useMemo(() => {
    if (!currentProcess) return [];
    return currentProcess.workItems.filter(wi => wi.work_phase === selectedPhase);
  }, [currentProcess, selectedPhase]);

  const selectedWorkItem = useMemo(() => {
    if (!selectedWorkItemId || !currentProcess) return null;
    return currentProcess.workItems.find(wi => wi.id === selectedWorkItemId) || null;
  }, [selectedWorkItemId, currentProcess]);

  // 커스텀 복사 확인 후 수정
  const ensureCustom = useCallback(async () => {
    if (isCustom) return true;
    try {
      const res = await copyWorkStandard(workInstructionNo, routingVersionId);
      if (res.success) {
        await loadData();
        setIsCustom(true);
        return true;
      }
    } catch (err) {
      toast.error("원본 복사에 실패했습니다");
    }
    return false;
  }, [isCustom, workInstructionNo, routingVersionId, loadData]);

  // 작업항목 추가
  const handleAddWorkItem = useCallback(async () => {
    if (!addItemTitle.trim()) { toast.error("제목을 입력하세요"); return; }
    const ok = await ensureCustom();
    if (!ok || !currentProcess) return;

    const newItem: WIWorkItem = {
      id: `temp-${Date.now()}`,
      routing_detail_id: currentProcess.routing_detail_id,
      work_phase: selectedPhase,
      title: addItemTitle.trim(),
      is_required: addItemRequired,
      sort_order: currentWorkItems.length + 1,
      details: [],
    };

    setProcesses(prev => {
      const next = [...prev];
      next[selectedProcessIdx] = {
        ...next[selectedProcessIdx],
        workItems: [...next[selectedProcessIdx].workItems, newItem],
      };
      return next;
    });

    setAddItemTitle("");
    setAddItemRequired("Y");
    setAddItemOpen(false);
    setDirty(true);
    setSelectedWorkItemId(newItem.id!);
  }, [addItemTitle, addItemRequired, ensureCustom, currentProcess, selectedPhase, currentWorkItems, selectedProcessIdx]);

  // 작업항목 삭제
  const handleDeleteWorkItem = useCallback(async (id: string) => {
    const ok = await ensureCustom();
    if (!ok) return;

    setProcesses(prev => {
      const next = [...prev];
      next[selectedProcessIdx] = {
        ...next[selectedProcessIdx],
        workItems: next[selectedProcessIdx].workItems.filter(wi => wi.id !== id),
      };
      return next;
    });
    if (selectedWorkItemId === id) setSelectedWorkItemId(null);
    setDirty(true);
  }, [ensureCustom, selectedProcessIdx, selectedWorkItemId]);

  // 상세 추가
  const handleAddDetail = useCallback(async () => {
    if (!addDetailContent.trim() && addDetailType !== "production_result" && addDetailType !== "material_input") {
      toast.error("내용을 입력하세요");
      return;
    }
    if (!selectedWorkItemId) return;
    const ok = await ensureCustom();
    if (!ok) return;

    const content = addDetailContent.trim() ||
      DETAIL_TYPES.find(d => d.value === addDetailType)?.label || addDetailType;

    const newDetail: WIWorkItemDetail = {
      id: `temp-detail-${Date.now()}`,
      work_item_id: selectedWorkItemId,
      detail_type: addDetailType,
      content,
      is_required: addDetailRequired,
      sort_order: (selectedWorkItem?.details?.length || 0) + 1,
    };

    setProcesses(prev => {
      const next = [...prev];
      const workItems = [...next[selectedProcessIdx].workItems];
      const wiIdx = workItems.findIndex(wi => wi.id === selectedWorkItemId);
      if (wiIdx >= 0) {
        workItems[wiIdx] = {
          ...workItems[wiIdx],
          details: [...(workItems[wiIdx].details || []), newDetail],
          detail_count: (workItems[wiIdx].detail_count || 0) + 1,
        };
      }
      next[selectedProcessIdx] = { ...next[selectedProcessIdx], workItems };
      return next;
    });

    setAddDetailContent("");
    setAddDetailType("checklist");
    setAddDetailRequired("N");
    setAddDetailOpen(false);
    setDirty(true);
  }, [addDetailContent, addDetailType, addDetailRequired, selectedWorkItemId, selectedWorkItem, ensureCustom, selectedProcessIdx]);

  // 상세 삭제
  const handleDeleteDetail = useCallback(async (detailId: string) => {
    if (!selectedWorkItemId) return;
    const ok = await ensureCustom();
    if (!ok) return;

    setProcesses(prev => {
      const next = [...prev];
      const workItems = [...next[selectedProcessIdx].workItems];
      const wiIdx = workItems.findIndex(wi => wi.id === selectedWorkItemId);
      if (wiIdx >= 0) {
        workItems[wiIdx] = {
          ...workItems[wiIdx],
          details: (workItems[wiIdx].details || []).filter(d => d.id !== detailId),
          detail_count: Math.max(0, (workItems[wiIdx].detail_count || 1) - 1),
        };
      }
      next[selectedProcessIdx] = { ...next[selectedProcessIdx], workItems };
      return next;
    });
    setDirty(true);
  }, [selectedWorkItemId, ensureCustom, selectedProcessIdx]);

  // 저장
  const handleSave = useCallback(async () => {
    if (!currentProcess) return;
    setSaving(true);
    try {
      const ok = await ensureCustom();
      if (!ok) return;

      const res = await saveWIWorkStandard(
        workInstructionNo,
        currentProcess.routing_detail_id,
        currentProcess.workItems
      );
      if (res.success) {
        toast.success("공정작업기준이 저장되었습니다");
        setDirty(false);
        await loadData();
      } else {
        toast.error("저장에 실패했습니다");
      }
    } catch (err) {
      toast.error("저장 중 오류가 발생했습니다");
    } finally {
      setSaving(false);
    }
  }, [currentProcess, ensureCustom, workInstructionNo, loadData]);

  // 원본으로 초기화
  const handleReset = useCallback(async () => {
    if (!confirm("커스터마이징한 내용을 모두 삭제하고 원본으로 되돌리시겠습니까?")) return;
    try {
      const res = await resetWIWorkStandard(workInstructionNo);
      if (res.success) {
        toast.success("원본으로 초기화되었습니다");
        await loadData();
      }
    } catch (err) {
      toast.error("초기화에 실패했습니다");
    }
  }, [workInstructionNo, loadData]);

  const getDetailTypeLabel = (type: string) =>
    DETAIL_TYPES.find(d => d.value === type)?.label || type;

  return (
    <Dialog open={open} onOpenChange={v => { if (!v) onClose(); }}>
      <DialogContent className="max-w-[95vw] sm:max-w-[1200px] h-[85vh] flex flex-col p-0 gap-0">
        <DialogHeader className="px-6 py-4 border-b shrink-0">
          <DialogTitle className="text-base flex items-center gap-2">
            <ClipboardCheck className="w-4 h-4" />
            공정작업기준 수정 - {itemName}
            {routingName && <Badge variant="secondary" className="text-xs ml-2">{routingName}</Badge>}
            {isCustom && <Badge variant="outline" className="text-xs ml-1 border-amber-300 text-amber-700">커스텀</Badge>}
          </DialogTitle>
          <DialogDescription className="text-xs">
            작업지시 [{workInstructionNo}]에 대한 공정작업기준을 수정합니다. 원본에 영향을 주지 않습니다.
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex-1 flex items-center justify-center">
            <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
          </div>
        ) : processes.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
            <AlertCircle className="w-10 h-10 mb-3 opacity-30" />
            <p className="text-sm">라우팅에 등록된 공정이 없습니다</p>
          </div>
        ) : (
          <div className="flex-1 flex flex-col overflow-hidden">
            {/* 공정 탭 */}
            <div className="flex items-center gap-1 px-4 py-2 border-b bg-muted/30 overflow-x-auto shrink-0">
              {processes.map((proc, idx) => (
                <Button
                  key={proc.routing_detail_id}
                  variant={selectedProcessIdx === idx ? "default" : "ghost"}
                  size="sm"
                  className={cn("text-xs shrink-0 h-8", selectedProcessIdx === idx && "shadow-sm")}
                  onClick={() => {
                    setSelectedProcessIdx(idx);
                    setSelectedWorkItemId(null);
                  }}
                >
                  <span className="mr-1.5 font-mono text-[10px] opacity-70">{proc.seq_no}.</span>
                  {proc.process_name}
                  {proc.workItems.length > 0 && (
                    <Badge variant="secondary" className="ml-1.5 text-[10px] h-4 px-1">{proc.workItems.length}</Badge>
                  )}
                </Button>
              ))}
            </div>

            {/* 작업 단계 탭 */}
            <div className="flex items-center gap-1 px-4 py-2 border-b shrink-0">
              {PHASES.map(phase => {
                const count = currentProcess?.workItems.filter(wi => wi.work_phase === phase.key).length || 0;
                return (
                  <Button
                    key={phase.key}
                    variant={selectedPhase === phase.key ? "secondary" : "ghost"}
                    size="sm"
                    className="text-xs h-7"
                    onClick={() => { setSelectedPhase(phase.key); setSelectedWorkItemId(null); }}
                  >
                    {phase.label}
                    {count > 0 && <Badge variant="outline" className="ml-1 text-[10px] h-4 px-1">{count}</Badge>}
                  </Button>
                );
              })}
            </div>

            {/* 작업항목 + 상세 split */}
            <div className="flex-1 flex overflow-hidden">
              {/* 좌측: 작업항목 목록 */}
              <div className="w-[280px] shrink-0 border-r flex flex-col overflow-hidden">
                <div className="flex items-center justify-between px-3 py-2 border-b bg-muted/20 shrink-0">
                  <span className="text-xs font-semibold">작업항목</span>
                  <Button variant="ghost" size="icon" className="h-6 w-6" onClick={() => { setAddItemTitle(""); setAddItemOpen(true); }}>
                    <Plus className="w-3.5 h-3.5" />
                  </Button>
                </div>
                <div className="flex-1 overflow-y-auto p-2 space-y-1">
                  {currentWorkItems.length === 0 ? (
                    <div className="text-xs text-muted-foreground text-center py-6">작업항목이 없습니다</div>
                  ) : currentWorkItems.map((wi) => (
                    <div
                      key={wi.id}
                      className={cn(
                        "group rounded-md border p-2.5 cursor-pointer transition-colors",
                        selectedWorkItemId === wi.id ? "border-primary bg-primary/5" : "hover:bg-muted/50"
                      )}
                      onClick={() => setSelectedWorkItemId(wi.id!)}
                    >
                      <div className="flex items-start justify-between gap-1">
                        <div className="min-w-0 flex-1">
                          <div className="text-xs font-medium truncate">{wi.title}</div>
                          <div className="flex items-center gap-1.5 mt-1">
                            {wi.is_required === "Y" && <Badge variant="destructive" className="text-[9px] h-4 px-1">필수</Badge>}
                            <span className="text-[10px] text-muted-foreground">상세 {wi.details?.length || wi.detail_count || 0}건</span>
                          </div>
                        </div>
                        <Button
                          variant="ghost" size="icon"
                          className="h-5 w-5 opacity-0 group-hover:opacity-100 shrink-0"
                          onClick={e => { e.stopPropagation(); handleDeleteWorkItem(wi.id!); }}
                        >
                          <Trash2 className="w-3 h-3 text-destructive" />
                        </Button>
                      </div>
                    </div>
                  ))}
                </div>
              </div>

              {/* 우측: 상세 목록 */}
              <div className="flex-1 flex flex-col overflow-hidden">
                {!selectedWorkItem ? (
                  <div className="flex-1 flex flex-col items-center justify-center text-muted-foreground">
                    <ChevronRight className="w-8 h-8 mb-2 opacity-20" />
                    <p className="text-xs">좌측에서 작업항목을 선택하세요</p>
                  </div>
                ) : (
                  <>
                    <div className="flex items-center justify-between px-4 py-2 border-b bg-muted/20 shrink-0">
                      <div>
                        <span className="text-xs font-semibold">{selectedWorkItem.title}</span>
                        <span className="text-[10px] text-muted-foreground ml-2">상세 항목</span>
                      </div>
                      <Button variant="ghost" size="sm" className="h-6 text-xs" onClick={() => { setAddDetailContent(""); setAddDetailType("checklist"); setAddDetailOpen(true); }}>
                        <Plus className="w-3 h-3 mr-1" /> 상세 추가
                      </Button>
                    </div>
                    <div className="flex-1 overflow-y-auto p-3 space-y-2">
                      {(!selectedWorkItem.details || selectedWorkItem.details.length === 0) ? (
                        <div className="text-xs text-muted-foreground text-center py-8">상세 항목이 없습니다</div>
                      ) : selectedWorkItem.details.map((detail, dIdx) => (
                        <div key={detail.id || dIdx} className="group flex items-start gap-2 rounded-md border p-3 hover:bg-muted/30">
                          <GripVertical className="w-3.5 h-3.5 mt-0.5 text-muted-foreground/30 shrink-0" />
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                              <Badge variant="outline" className="text-[10px] h-4 px-1.5 shrink-0">
                                {getDetailTypeLabel(detail.detail_type || "checklist")}
                              </Badge>
                              {detail.is_required === "Y" && <Badge variant="destructive" className="text-[9px] h-4 px-1">필수</Badge>}
                            </div>
                            <p className="text-xs mt-1 break-all">{detail.content || "-"}</p>
                            {detail.remark && <p className="text-[10px] text-muted-foreground mt-0.5">{detail.remark}</p>}
                            {detail.detail_type === "inspection" && (detail.lower_limit || detail.upper_limit) && (
                              <div className="text-[10px] text-muted-foreground mt-1">
                                범위: {detail.lower_limit || "-"} ~ {detail.upper_limit || "-"} {detail.unit || ""}
                              </div>
                            )}
                          </div>
                          <Button
                            variant="ghost" size="icon"
                            className="h-5 w-5 opacity-0 group-hover:opacity-100 shrink-0"
                            onClick={() => handleDeleteDetail(detail.id!)}
                          >
                            <Trash2 className="w-3 h-3 text-destructive" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        )}

        <DialogFooter className="px-6 py-3 border-t shrink-0 flex items-center justify-between">
          <div>
            {isCustom && (
              <Button variant="outline" size="sm" className="text-xs" onClick={handleReset}>
                <RotateCcw className="w-3.5 h-3.5 mr-1.5" /> 원본으로 초기화
              </Button>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" onClick={onClose}>닫기</Button>
            <Button onClick={handleSave} disabled={saving || (!dirty && isCustom)}>
              {saving ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <Save className="w-4 h-4 mr-1.5" />}
              저장
            </Button>
          </div>
        </DialogFooter>

        {/* 작업항목 추가 다이얼로그 */}
        <Dialog open={addItemOpen} onOpenChange={setAddItemOpen}>
          <DialogContent className="max-w-[95vw] sm:max-w-[400px]" onClick={e => e.stopPropagation()}>
            <DialogHeader>
              <DialogTitle className="text-base">작업항목 추가</DialogTitle>
              <DialogDescription className="text-xs">
                {PHASES.find(p => p.key === selectedPhase)?.label} 단계에 작업항목을 추가합니다.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-3">
              <div>
                <Label className="text-xs">제목 *</Label>
                <Input value={addItemTitle} onChange={e => setAddItemTitle(e.target.value)} placeholder="작업항목 제목" className="h-8 text-xs mt-1" />
              </div>
              <div className="flex items-center gap-2">
                <Checkbox checked={addItemRequired === "Y"} onCheckedChange={v => setAddItemRequired(v ? "Y" : "N")} />
                <Label className="text-xs">필수 항목</Label>
              </div>
            </div>
            <DialogFooter className="gap-2">
              <Button variant="outline" size="sm" onClick={() => setAddItemOpen(false)}>취소</Button>
              <Button size="sm" onClick={handleAddWorkItem}>추가</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>

        {/* 상세 추가 다이얼로그 */}
        <Dialog open={addDetailOpen} onOpenChange={setAddDetailOpen}>
          <DialogContent className="max-w-[95vw] sm:max-w-[450px]" onClick={e => e.stopPropagation()}>
            <DialogHeader>
              <DialogTitle className="text-base">상세 항목 추가</DialogTitle>
              <DialogDescription className="text-xs">
                "{selectedWorkItem?.title}"에 상세 항목을 추가합니다.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-3">
              <div>
                <Label className="text-xs">유형</Label>
                <Select value={addDetailType} onValueChange={setAddDetailType}>
                  <SelectTrigger className="h-8 text-xs mt-1"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {DETAIL_TYPES.map(dt => (
                      <SelectItem key={dt.value} value={dt.value} className="text-xs">{dt.label}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label className="text-xs">내용</Label>
                <Input value={addDetailContent} onChange={e => setAddDetailContent(e.target.value)} placeholder="상세 내용 입력" className="h-8 text-xs mt-1" />
              </div>
              <div className="flex items-center gap-2">
                <Checkbox checked={addDetailRequired === "Y"} onCheckedChange={v => setAddDetailRequired(v ? "Y" : "N")} />
                <Label className="text-xs">필수 항목</Label>
              </div>
            </div>
            <DialogFooter className="gap-2">
              <Button variant="outline" size="sm" onClick={() => setAddDetailOpen(false)}>취소</Button>
              <Button size="sm" onClick={handleAddDetail}>추가</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </DialogContent>
    </Dialog>
  );
}
