"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 { DataFlowAPI, DataFlowDiagram } from "@/lib/api/dataflow";
import { toast } from "sonner";
import { useAuth } from "@/hooks/useAuth";

interface DataFlowListProps {
  onDesignDiagram: (diagram: DataFlowDiagram | null) => void;
}

export default function DataFlowList({ onDesignDiagram }: DataFlowListProps) {
  const { user } = useAuth();
  const [diagrams, setDiagrams] = useState<DataFlowDiagram[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [total, setTotal] = useState(0);

  // 사용자 회사 코드 가져오기 (기본값: "*")
  const companyCode = user?.company_code || user?.companyCode || "*";

  // 모달 상태
  const [showCopyModal, setShowCopyModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [selectedDiagramForAction, setSelectedDiagramForAction] = useState<DataFlowDiagram | null>(null);

  // 목록 로드 함수 분리
  const loadDiagrams = useCallback(async () => {
    try {
      setLoading(true);
      const response = await DataFlowAPI.getJsonDataFlowDiagrams(currentPage, 20, searchTerm, companyCode);

      // JSON API 응답을 기존 형식으로 변환
      const convertedDiagrams = response.diagrams.map((diagram) => {
        // relationships 구조 분석
        const relationships = diagram.relationships || {};

        // 테이블 정보 추출
        const tables: string[] = [];
        if (relationships.fromTable?.tableName) {
          tables.push(relationships.fromTable.tableName);
        }
        if (
          relationships.toTable?.tableName &&
          relationships.toTable.tableName !== relationships.fromTable?.tableName
        ) {
          tables.push(relationships.toTable.tableName);
        }

        // 관계 수 계산 (actionGroups 기준)
        const actionGroups = relationships.actionGroups || [];
        const relationshipCount = actionGroups.reduce((count: number, group: any) => {
          return count + (group.actions?.length || 0);
        }, 0);

        return {
          diagramId: diagram.diagram_id,
          relationshipId: diagram.diagram_id, // 호환성을 위해 추가
          diagramName: diagram.diagram_name,
          connectionType: relationships.connectionType || "data_save", // 실제 연결 타입 사용
          relationshipType: "multi-relationship", // 다중 관계 타입
          relationshipCount: relationshipCount || 1, // 최소 1개는 있다고 가정
          tableCount: tables.length,
          tables: tables,
          companyCode: diagram.company_code, // 회사 코드 추가
          createdAt: new Date(diagram.created_at || new Date()),
          createdBy: diagram.created_by || "SYSTEM",
          updatedAt: new Date(diagram.updated_at || diagram.created_at || new Date()),
          updatedBy: diagram.updated_by || "SYSTEM",
          lastUpdated: diagram.updated_at || diagram.created_at || new Date().toISOString(),
        };
      });

      setDiagrams(convertedDiagrams);
      setTotal(response.pagination.total || 0);
      setTotalPages(Math.max(1, Math.ceil((response.pagination.total || 0) / 20)));
    } catch (error) {
      console.error("관계 목록 조회 실패", error);
      toast.error("관계 목록을 불러오는데 실패했습니다.");
    } finally {
      setLoading(false);
    }
  }, [currentPage, searchTerm, companyCode]);

  // 관계 목록 로드
  useEffect(() => {
    loadDiagrams();
  }, [loadDiagrams]);

  const handleDelete = (diagram: DataFlowDiagram) => {
    setSelectedDiagramForAction(diagram);
    setShowDeleteModal(true);
  };

  const handleCopy = (diagram: DataFlowDiagram) => {
    setSelectedDiagramForAction(diagram);
    setShowCopyModal(true);
  };

  // 복사 확인
  const handleConfirmCopy = async () => {
    if (!selectedDiagramForAction) return;

    try {
      setLoading(true);
      const copiedDiagram = await DataFlowAPI.copyJsonDataFlowDiagram(
        selectedDiagramForAction.diagramId,
        companyCode,
        undefined,
        user?.userId || "SYSTEM",
      );
      toast.success(`관계가 성공적으로 복사되었습니다: ${copiedDiagram.diagram_name}`);

      // 목록 새로고침
      await loadDiagrams();
    } catch (error) {
      console.error("관계 복사 실패:", error);
      toast.error("관계 복사에 실패했습니다.");
    } finally {
      setLoading(false);
      setShowCopyModal(false);
      setSelectedDiagramForAction(null);
    }
  };

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

    try {
      setLoading(true);
      await DataFlowAPI.deleteJsonDataFlowDiagram(selectedDiagramForAction.diagramId, companyCode);
      toast.success(`관계가 삭제되었습니다: ${selectedDiagramForAction.diagramName}`);

      // 목록 새로고침
      await loadDiagrams();
    } catch (error) {
      console.error("관계 삭제 실패:", error);
      toast.error("관계 삭제에 실패했습니다.");
    } finally {
      setLoading(false);
      setShowDeleteModal(false);
      setSelectedDiagramForAction(null);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-8">
        <div className="text-gray-500">로딩 중...</div>
      </div>
    );
  }

  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={() => onDesignDiagram(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" />
              데이터 흐름 관계 ({total})
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>관계명</TableHead>
                <TableHead>회사 코드</TableHead>
                <TableHead>테이블 수</TableHead>
                <TableHead>관계 수</TableHead>
                <TableHead>최근 수정</TableHead>
                <TableHead>작업</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {diagrams.map((diagram) => (
                <TableRow key={diagram.diagramId} className="hover:bg-gray-50">
                  <TableCell>
                    <div>
                      <div className="flex items-center font-medium text-gray-900">
                        <Database className="mr-2 h-4 w-4 text-gray-500" />
                        {diagram.diagramName}
                      </div>
                      <div className="mt-1 text-sm text-gray-500">
                        테이블: {diagram.tables.slice(0, 3).join(", ")}
                        {diagram.tables.length > 3 && ` 외 ${diagram.tables.length - 3}개`}
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{diagram.companyCode || "*"}</TableCell>
                  <TableCell>
                    <div className="flex items-center">
                      <Database className="mr-1 h-3 w-3 text-gray-400" />
                      {diagram.tableCount}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center">
                      <Network className="mr-1 h-3 w-3 text-gray-400" />
                      {diagram.relationshipCount}
                    </div>
                  </TableCell>
                  <TableCell>
                    <div className="flex items-center text-sm text-gray-600">
                      <Calendar className="mr-1 h-3 w-3 text-gray-400" />
                      {new Date(diagram.updatedAt).toLocaleDateString()}
                    </div>
                    <div className="flex items-center text-xs text-gray-400">
                      <User className="mr-1 h-3 w-3" />
                      {diagram.updatedBy}
                    </div>
                  </TableCell>
                  <TableCell>
                    <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={() => onDesignDiagram(diagram)}>
                          <Network className="mr-2 h-4 w-4" />
                          수정
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleCopy(diagram)}>
                          <Copy className="mr-2 h-4 w-4" />
                          복사
                        </DropdownMenuItem>
                        <DropdownMenuItem onClick={() => handleDelete(diagram)} className="text-red-600">
                          <Trash2 className="mr-2 h-4 w-4" />
                          삭제
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>

          {diagrams.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>

      {/* 페이지네이션 */}
      {totalPages > 1 && (
        <div className="flex items-center justify-center space-x-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
            disabled={currentPage === 1}
          >
            이전
          </Button>
          <span className="text-sm text-gray-600">
            {currentPage} / {totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
            disabled={currentPage === totalPages}
          >
            다음
          </Button>
        </div>
      )}

      {/* 복사 확인 모달 */}
      <Dialog open={showCopyModal} onOpenChange={setShowCopyModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>관계 복사</DialogTitle>
            <DialogDescription>
              &ldquo;{selectedDiagramForAction?.diagramName}&rdquo; 관계를 복사하시겠습니까?
              <br />
              새로운 관계는 원본 이름 뒤에 (1), (2), (3)... 형태로 생성됩니다.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCopyModal(false)}>
              취소
            </Button>
            <Button onClick={handleConfirmCopy} disabled={loading}>
              {loading ? "복사 중..." : "복사"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 모달 */}
      <Dialog open={showDeleteModal} onOpenChange={setShowDeleteModal}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="text-red-600">관계 삭제</DialogTitle>
            <DialogDescription>
              &ldquo;{selectedDiagramForAction?.diagramName}&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>
  );
}
