"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { MoreHorizontal, Trash2, Copy, Plus, Search, Network, Database, Calendar, User } from "lucide-react";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";
import { apiClient } from "@/lib/api/client";

// 노드 플로우 타입 정의
interface NodeFlow {
  flowId: number;
  flowName: string;
  flowDescription: string;
  createdAt: string;
  updatedAt: string;
}

interface DataFlowListProps {
  onLoadFlow: (flowId: number | null) => void;
}

export default function DataFlowList({ onLoadFlow }: DataFlowListProps) {
  const { user } = useAuth();
  const [flows, setFlows] = useState<NodeFlow[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");

  // 모달 상태
  const [showCopyModal, setShowCopyModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedFlow, setSelectedFlow] = useState<NodeFlow | null>(null);

  // 노드 플로우 목록 로드
  const loadFlows = useCallback(async () => {
    try {
      setLoading(true);
      const response = await apiClient.get("/dataflow/node-flows");

      if (response.data.success) {
        setFlows(response.data.data);
      } else {
        throw new Error(response.data.message || "플로우 목록 조회 실패");
      }
    } catch (error) {
      console.error("플로우 목록 조회 실패", error);
      toast.error("플로우 목록을 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  }, []);

  // 플로우 목록 로드
  useEffect(() => {
    loadFlows();
  }, [loadFlows]);

  // 플로우 삭제
  const handleDelete = (flow: NodeFlow) => {
    setSelectedFlow(flow);
    setShowDeleteModal(true);
  };

  // 플로우 복사
  const handleCopy = async (flow: NodeFlow) => {
    try {
      setLoading(true);

      // 원본 플로우 데이터 가져오기
      const response = await apiClient.get(`/dataflow/node-flows/${flow.flowId}`);

      if (!response.data.success) {
        throw new Error(response.data.message || "플로우 조회 실패");
      }

      const originalFlow = response.data.data;

      // 복사본 저장
      const copyResponse = await apiClient.post("/dataflow/node-flows", {
        flowName: `${flow.flowName} (복사본)`,
        flowDescription: flow.flowDescription,
        flowData: originalFlow.flowData,
      });

      if (copyResponse.data.success) {
        toast.success(`플로우가 성공적으로 복사되었습니다`);
        await loadFlows();
      } else {
        throw new Error(copyResponse.data.message || "플로우 복사 실패");
      }
    } catch (error) {
      console.error("플로우 복사 실패:", error);
      toast.error("플로우 복사에 실패했습니다.");
    } finally {
      setLoading(false);
    }
  };

  // 삭제 확인
  const handleConfirmDelete = async () => {
    if (!selectedFlow) return;

    try {
      setLoading(true);
      const response = await apiClient.delete(`/dataflow/node-flows/${selectedFlow.flowId}`);

      if (response.data.success) {
        toast.success(`플로우가 삭제되었습니다: ${selectedFlow.flowName}`);
        await loadFlows();
      } else {
        throw new Error(response.data.message || "플로우 삭제 실패");
      }
    } catch (error) {
      console.error("플로우 삭제 실패:", error);
      toast.error("플로우 삭제에 실패했습니다.");
    } finally {
      setLoading(false);
      setShowDeleteModal(false);
      setSelectedFlow(null);
    }
  };

  // 검색 필터링
  const filteredFlows = flows.filter(
    (flow) =>
      flow.flowName.toLowerCase().includes(searchTerm.toLowerCase()) ||
      flow.flowDescription.toLowerCase().includes(searchTerm.toLowerCase()),
  );

  return (
    <div className="space-y-4">
      {/* 검색 및 필터 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-2">
          <div className="relative">
            <Search className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 transform text-gray-400" />
            <Input
              placeholder="플로우명, 설명으로 검색..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="w-80 pl-10"
            />
          </div>
        </div>
        <Button className="bg-blue-600 hover:bg-blue-700" onClick={() => onLoadFlow(null)}>
          <Plus className="mr-2 h-4 w-4" />새 플로우 생성
        </Button>
      </div>

      {/* 플로우 목록 테이블 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <span className="flex items-center">
              <Network className="mr-2 h-5 w-5" />
              노드 플로우 목록 ({filteredFlows.length})
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <div className="text-gray-500">로딩 중...</div>
            </div>
          ) : (
            <>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>플로우명</TableHead>
                    <TableHead>설명</TableHead>
                    <TableHead>생성일</TableHead>
                    <TableHead>최근 수정</TableHead>
                    <TableHead className="text-right">작업</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredFlows.map((flow) => (
                    <TableRow
                      key={flow.flowId}
                      className="cursor-pointer hover:bg-gray-50"
                      onClick={() => onLoadFlow(flow.flowId)}
                    >
                      <TableCell>
                        <div className="flex items-center font-medium text-gray-900">
                          <Network className="mr-2 h-4 w-4 text-blue-500" />
                          {flow.flowName}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm text-gray-500">{flow.flowDescription || "설명 없음"}</div>
                      </TableCell>
                      <TableCell>
                        <div className="text-muted-foreground flex items-center text-sm">
                          <Calendar className="mr-1 h-3 w-3 text-gray-400" />
                          {new Date(flow.createdAt).toLocaleDateString()}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-muted-foreground flex items-center text-sm">
                          <Calendar className="mr-1 h-3 w-3 text-gray-400" />
                          {new Date(flow.updatedAt).toLocaleDateString()}
                        </div>
                      </TableCell>
                      <TableCell onClick={(e) => e.stopPropagation()}>
                        <div className="flex justify-end">
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" className="h-8 w-8 p-0">
                                <MoreHorizontal className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem onClick={() => onLoadFlow(flow.flowId)}>
                                <Network className="mr-2 h-4 w-4" />
                                불러오기
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => handleCopy(flow)}>
                                <Copy className="mr-2 h-4 w-4" />
                                복사
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => handleDelete(flow)} className="text-destructive">
                                <Trash2 className="mr-2 h-4 w-4" />
                                삭제
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>

              {filteredFlows.length === 0 && (
                <div className="py-8 text-center text-gray-500">
                  <Network className="mx-auto mb-4 h-12 w-12 text-gray-300" />
                  <div className="mb-2 text-lg font-medium">플로우가 없습니다</div>
                  <div className="text-sm">새 플로우를 생성하여 노드 기반 데이터 제어를 설계해보세요.</div>
                </div>
              )}
            </>
          )}
        </CardContent>
      </Card>

      {/* 삭제 확인 모달 */}
      <Dialog open={showDeleteModal} onOpenChange={setShowDeleteModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="text-red-600">플로우 삭제</DialogTitle>
            <DialogDescription>
              &ldquo;{selectedFlow?.flowName}&rdquo; 플로우를 완전히 삭제하시겠습니까?
              <br />
              <span className="font-medium text-red-600">
                이 작업은 되돌릴 수 없으며, 모든 플로우 정보가 영구적으로 삭제됩니다.
              </span>
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowDeleteModal(false)}>
              취소
            </Button>
            <Button variant="destructive" onClick={handleConfirmDelete} disabled={loading}>
              {loading ? "삭제 중..." : "삭제"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
