// components/form-data-stat/form-data-stat-table.tsx
"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { RefreshCw, Check, ChevronsUpDown } from "lucide-react";
import { type ColumnDef } from "@tanstack/react-table";
import { ClientDataTableColumnHeaderSimple } from "@/components/client-data-table/data-table-column-simple-header";
import { ClientDataTable } from "@/components/client-data-table/data-table";
import { cn } from "@/lib/utils";
import { toast } from "sonner";
import type { DataTableAdvancedFilterField } from "@/types/table";
import { Progress } from "@/components/ui/progress";
import { getVendorFormStatus, getProjectsWithContracts } from "@/lib/forms/stat";
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@/components/ui/command";

// 타입 정의
interface VendorFormStatus {
  vendorId: number;
  vendorName: string;
  formCount: number;
  tagCount: number;
  totalFields: number;
  completedFields: number;
  completionRate: number;
}

interface Project {
  id: number;
  projectCode: string;
  projectName: string;
}

interface VendorFormStatusTableProps {
  initialData?: VendorFormStatus[];
}

// 완료율에 따른 색상 반환
const getCompletionColor = (rate: number) => {
  if (rate >= 80) return "text-green-600";
  if (rate >= 50) return "text-yellow-600";
  if (rate >= 20) return "text-orange-600";
  return "text-red-600";
};

// 완료율에 따른 Badge variant 반환
const getCompletionBadgeVariant = (rate: number): "default" | "secondary" | "destructive" | "outline" => {
  if (rate >= 80) return "default";
  if (rate >= 50) return "secondary";
  if (rate >= 20) return "outline";
  return "destructive";
};

// 프로젝트 선택 컴포넌트
function ProjectSelectorWithContracts({ 
  selectedProject,
  onProjectSelect,
  projects,
  isLoading
}: {
  selectedProject: Project | null;
  onProjectSelect: (project: Project | null) => void;
  projects: Project[];
  isLoading: boolean;
}) {
  const [open, setOpen] = React.useState(false);
  const [searchTerm, setSearchTerm] = React.useState("");

  // 검색어로 필터링
  const filteredProjects = React.useMemo(() => {
    if (!searchTerm.trim()) return projects;
    
    const lowerSearch = searchTerm.toLowerCase();
    return projects.filter(
      project => 
        project.projectCode.toLowerCase().includes(lowerSearch) || 
        project.projectName.toLowerCase().includes(lowerSearch)
    );
  }, [projects, searchTerm]);

  const handleSelectProject = (project: Project | null) => {
    onProjectSelect(project);
    setOpen(false);
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className="w-full justify-between"
          disabled={isLoading}
        >
          {selectedProject
            ? `${selectedProject.projectCode} - ${selectedProject.projectName}`
            : "프로젝트를 선택하세요..."}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[400px] p-0">
        <Command>
          <CommandInput
            placeholder="프로젝트 코드/이름 검색..."
            onValueChange={setSearchTerm}
          />
          <CommandList className="max-h-[300px]">
            <CommandEmpty>검색 결과가 없습니다</CommandEmpty>
            {isLoading ? (
              <div className="py-6 text-center text-sm">로딩 중...</div>
            ) : (
              <CommandGroup>
                {/* 전체 옵션 추가 */}
                <CommandItem
                  value="all"
                  onSelect={() => handleSelectProject(null)}
                >
                  <Check
                    className={cn(
                      "mr-2 h-4 w-4",
                      selectedProject === null ? "opacity-100" : "opacity-0"
                    )}
                  />
                  <span className="font-medium">전체 프로젝트</span>
                </CommandItem>
                {/* 프로젝트 목록 */}
                {filteredProjects.map((project) => (
                  <CommandItem
                    key={project.id}
                    value={`${project.projectCode} ${project.projectName}`}
                    onSelect={() => handleSelectProject(project)}
                  >
                    <Check
                      className={cn(
                        "mr-2 h-4 w-4",
                        selectedProject?.id === project.id
                          ? "opacity-100"
                          : "opacity-0"
                      )}
                    />
                    <span className="font-medium">{project.projectCode}</span>
                    <span className="ml-2 text-gray-500 truncate">- {project.projectName}</span>
                  </CommandItem>
                ))}
              </CommandGroup>
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}

export function VendorFormStatusTable({
  initialData = [],
}: VendorFormStatusTableProps) {
  const [data, setData] = React.useState<VendorFormStatus[]>(initialData);
  const [isRefreshing, setIsRefreshing] = React.useState(false);
  const [selectedProject, setSelectedProject] = React.useState<Project | null>(null);
  const [projects, setProjects] = React.useState<Project[]>([]);
  const [isLoadingProjects, setIsLoadingProjects] = React.useState(false);

  // 프로젝트 목록 로드
  React.useEffect(() => {
    const loadProjects = async () => {
      setIsLoadingProjects(true);
      try {
        const projectsWithContracts = await getProjectsWithContracts();
        setProjects(projectsWithContracts);
        
        // 프로젝트가 하나만 있으면 자동 선택
        if (projectsWithContracts.length === 1) {
          setSelectedProject(projectsWithContracts[0]);
        }
      } catch (error) {
        console.error("프로젝트 목록 로드 오류:", error);
        toast.error("프로젝트 목록을 불러오는데 실패했습니다.");
      } finally {
        setIsLoadingProjects(false);
      }
    };

    loadProjects();
  }, []);

  // 프로젝트 변경 시 데이터 로드
  React.useEffect(() => {
    handleRefresh();
  }, [selectedProject]);

  // 데이터 새로고침
  const handleRefresh = React.useCallback(async () => {
    setIsRefreshing(true);
    try {
      const result = await getVendorFormStatus(selectedProject?.id);
      setData(result);
      if (selectedProject) {
        toast.success(`${selectedProject.projectCode} 데이터를 새로고침했습니다.`);
      } else {
        toast.success("전체 프로젝트 데이터를 새로고침했습니다.");
      }
    } catch (error) {
      console.error("Refresh error:", error);
      toast.error("새로고침 중 오류가 발생했습니다.");
    } finally {
      setIsRefreshing(false);
    }
  }, [selectedProject]);

  // 컬럼 정의 (기존과 동일)
  const columns: ColumnDef<VendorFormStatus>[] = React.useMemo(() => [
    {
      accessorKey: "vendorName",
      header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="벤더명" />,
      cell: ({ row }) => (
        <div className="font-medium">{row.original.vendorName}</div>
      ),
      size: 200,
      enablePinning: true,
      meta: { excelHeader: "벤더명" },
    },
    {
      accessorKey: "formCount",
      header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="Form 개수" />,
      cell: ({ row }) => (
        <div className="text-center">
          <Badge variant="outline">{row.original.formCount}</Badge>
        </div>
      ),
      size: 100,
      meta: { excelHeader: "Form 개수" },
    },
    {
      accessorKey: "tagCount",
      header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="Tag 개수" />,
      cell: ({ row }) => (
        <div className="text-center">
          <Badge variant="outline">{row.original.tagCount}</Badge>
        </div>
      ),
      size: 100,
      meta: { excelHeader: "Tag 개수" },
    },
    {
      accessorKey: "totalFields",
      header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="전체 필드" />,
      cell: ({ row }) => (
        <div className="text-center font-mono">
          {row.original.totalFields.toLocaleString()}
        </div>
      ),
      size: 100,
      meta: { excelHeader: "전체 필드" },
    },
    {
      accessorKey: "completedFields",
      header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="완료 필드" />,
      cell: ({ row }) => (
        <div className="text-center font-mono">
          {row.original.completedFields.toLocaleString()}
        </div>
      ),
      size: 100,
      meta: { excelHeader: "완료 필드" },
    },
    {
      accessorKey: "completionRate",
      header: ({ column }) => <ClientDataTableColumnHeaderSimple column={column} title="완료율" />,
      cell: ({ row }) => {
        const rate = row.original.completionRate;
        return (
          <div className="flex items-center gap-2">
            <Progress 
              value={rate} 
              className="w-[80px]"
            />
            <Badge 
              variant={getCompletionBadgeVariant(rate)}
              className={cn("min-w-[60px] justify-center", getCompletionColor(rate))}
            >
              {rate.toFixed(1)}%
            </Badge>
          </div>
        );
      },
      size: 180,
      meta: { excelHeader: "완료율" },
    },
    {
      id: "progress",
      header: "진행 상태",
      cell: ({ row }) => {
        const { completedFields, totalFields } = row.original;
        return (
          <div className="text-sm text-muted-foreground">
            {completedFields} / {totalFields}
          </div>
        );
      },
      size: 120,
      meta: { excelHeader: "진행 상태" },
    },
  ], []);

  // 필터 필드 정의
  const advancedFilterFields: DataTableAdvancedFilterField<VendorFormStatus>[] = [
    { id: "vendorName", label: "벤더명", type: "text" },
    { id: "formCount", label: "Form 개수", type: "number" },
    { id: "tagCount", label: "Tag 개수", type: "number" },
    { id: "completionRate", label: "완료율", type: "number" },
  ];

  // 요약 통계
  const summaryStats = React.useMemo(() => {
    const totalVendors = data.length;
    const totalForms = data.reduce((sum, v) => sum + v.formCount, 0);
    const totalTags = data.reduce((sum, v) => sum + v.tagCount, 0);
    const avgCompletionRate = data.length > 0
      ? data.reduce((sum, v) => sum + v.completionRate, 0) / data.length
      : 0;
    const fullCompletedVendors = data.filter(v => v.completionRate === 100).length;

    return {
      totalVendors,
      totalForms,
      totalTags,
      avgCompletionRate,
      fullCompletedVendors,
    };
  }, [data]);

  return (
    <div className={cn("w-full space-y-4")}>
      {/* 프로젝트 선택 */}
      <Card>
        <CardHeader>
          <CardTitle>프로젝트 선택</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center gap-4">
            <div className="flex-1">
              <ProjectSelectorWithContracts
                selectedProject={selectedProject}
                onProjectSelect={setSelectedProject}
                projects={projects}
                isLoading={isLoadingProjects}
              />
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={handleRefresh}
              disabled={isRefreshing}
            >
              <RefreshCw className={cn("h-4 w-4 mr-2", isRefreshing && "animate-spin")} />
              새로고침
            </Button>
          </div>
          {selectedProject && (
            <div className="mt-2 text-sm text-muted-foreground">
              선택된 프로젝트: {selectedProject.projectCode} - {selectedProject.projectName}
            </div>
          )}
        </CardContent>
      </Card>

      {/* 요약 카드 */}
      <div className="grid gap-4 md:grid-cols-5">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">전체 벤더</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{summaryStats.totalVendors}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">전체 Form</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{summaryStats.totalForms.toLocaleString()}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">전체 Tag</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{summaryStats.totalTags.toLocaleString()}</div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">평균 완료율</CardTitle>
          </CardHeader>
          <CardContent>
            <div className={cn("text-2xl font-bold", getCompletionColor(summaryStats.avgCompletionRate))}>
              {summaryStats.avgCompletionRate.toFixed(1)}%
            </div>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">완료 벤더</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {summaryStats.fullCompletedVendors} / {summaryStats.totalVendors}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 데이터 테이블 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle>
              벤더별 Form 입력 현황
              {selectedProject && (
                <span className="ml-2 text-sm font-normal text-muted-foreground">
                  ({selectedProject.projectCode})
                </span>
              )}
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent>
          {data.length > 0 ? (
            <ClientDataTable
              columns={columns}
              data={data}
              advancedFilterFields={advancedFilterFields}
              autoSizeColumns={true}
              compact={true}
              maxHeight="34rem"
              initialColumnPinning={{
                left: ["vendorName"],
              }}
              defaultSorting={[
                { id: "completionRate", desc: false }, // 완료율 낮은 순으로 정렬
              ]}
            />
          ) : (
            <div className="text-center py-8 text-muted-foreground">
              {selectedProject 
                ? "선택한 프로젝트에 대한 데이터가 없습니다."
                : "데이터가 없습니다."}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}