// app/evcp/menu-list/components/menu-list-table.tsx

"use client";

import { useState, useMemo } from "react";
import { useParams } from "next/navigation";
import { useTranslation } from "@/i18n/client";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { Search, Filter, ExternalLink } from "lucide-react";
import { toast } from "sonner";
import { ManagerSelect } from "./manager-select";
import { InitializeButton } from "./initialize-button";
import { ExportButton } from "./export-button";
import { toggleMenuActive } from "../servcie";

interface MenuAssignment {
  id: number;
  menuPath: string;
  menuTitle: string;
  menuDescription?: string | null;
  menuGroup?: string | null;
  sectionTitle: string;
  domain: string;
  isActive: boolean;
  createdAt: Date;
  updatedAt: Date;
  manager1Id?: number | null;
  manager2Id?: number | null;
  manager1Name?: string | null;
  manager1Email?: string | null;
  manager2Name?: string | null;
  manager2Email?: string | null;
}

interface User {
  id: number;
  name: string;
  email: string;
  domain: string;
}

interface MenuListTableProps {
  initialMenus: MenuAssignment[];
  initialUsers: User[];
}

export function MenuListTable({ initialMenus, initialUsers }: MenuListTableProps) {
  // URL에서 언어 파라미터 가져오기
  const params = useParams();
  const lng = (params?.lng as string) || 'ko';
  const { t } = useTranslation(lng, 'menu');
  
  // 안전한 번역 함수 (키가 없을 때 원본 키 반환)
  const safeTranslate = (key: string): string => {
    try {
      const translated = t(key);
      // 번역 키가 그대로 반환되는 경우 원본 키 사용
      if (translated === key) {
        return key;
      }
      return translated || key;
    } catch (error) {
      console.warn(`Translation failed for key: ${key}`, error);
      return key;
    }
  };
  
  const [searchQuery, setSearchQuery] = useState("");
  const [domainFilter, setDomainFilter] = useState<string>("all");
  const [sectionFilter, setSectionFilter] = useState<string>("all");
  const [statusFilter, setStatusFilter] = useState<string>("all");

  // 필터링된 메뉴 데이터
  const filteredMenus = useMemo(() => {
    return initialMenus.filter((menu) => {
      const translatedTitle = safeTranslate(menu.menuTitle);
      const translatedSection = safeTranslate(menu.sectionTitle);
      const translatedDescription = menu.menuDescription ? safeTranslate(menu.menuDescription) : '';
      
      const matchesSearch =
        translatedTitle.toLowerCase().includes(searchQuery.toLowerCase()) ||
        menu.menuPath.toLowerCase().includes(searchQuery.toLowerCase()) ||
        translatedSection.toLowerCase().includes(searchQuery.toLowerCase()) ||
        translatedDescription.toLowerCase().includes(searchQuery.toLowerCase());

      const matchesDomain = domainFilter === "all" || menu.domain === domainFilter;
      const matchesSection = sectionFilter === "all" || translatedSection === sectionFilter;
      const matchesStatus = statusFilter === "all" ||
        (statusFilter === "active" && menu.isActive) ||
        (statusFilter === "inactive" && !menu.isActive);

      return matchesSearch && matchesDomain && matchesSection && matchesStatus;
    });
  }, [initialMenus, searchQuery, domainFilter, sectionFilter, statusFilter, safeTranslate]);

  // 섹션 리스트 추출 (번역된 이름으로)
  const sections = useMemo(() => {
    const sectionSet = new Set(initialMenus.map(menu => safeTranslate(menu.sectionTitle)));
    return Array.from(sectionSet).sort();
  }, [initialMenus, safeTranslate]);

  // 도메인별 사용자 필터링
  const getFilteredUsers = (domain: string) => {
    return initialUsers.filter(user => user.domain === domain);
  };

  // 메뉴 활성화/비활성화 토글
  const handleToggleActive = async (menuPath: string, isActive: boolean) => {
    try {
      const result = await toggleMenuActive(menuPath, isActive);
      if (result.success) {
        toast.success(result.message);
      } else {
        toast.error(result.message);
      }
    } catch (error) {
      toast.error("메뉴 상태 변경 중 오류가 발생했습니다.");
    }
  };

  return (
    <div className="space-y-4">
      {/* 필터 영역 */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="flex-1">
          <div className="relative">
            <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
            <Input
              placeholder="메뉴명, 경로, 설명으로 검색..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="pl-8"
            />
          </div>
        </div>

        <div className="flex gap-2">
          <Select value={domainFilter} onValueChange={setDomainFilter}>
            <SelectTrigger className="w-[120px]">
              <SelectValue placeholder="도메인" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체 도메인</SelectItem>
              <SelectItem value="evcp">EVCP</SelectItem>
              <SelectItem value="partners">Partners</SelectItem>
            </SelectContent>
          </Select>

          <Select value={sectionFilter} onValueChange={setSectionFilter}>
            <SelectTrigger className="w-[150px]">
              <SelectValue placeholder="섹션" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체 섹션</SelectItem>
              {sections.map((section) => (
                <SelectItem key={section} value={section}>
                  {section}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger className="w-[100px]">
              <SelectValue placeholder="상태" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              <SelectItem value="active">활성</SelectItem>
              <SelectItem value="inactive">비활성</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 결과 요약, 엑셀 다운로드 및 초기화 버튼 */}
      <div className="flex items-center justify-between">
        <span className="text-sm text-muted-foreground">
          총 {filteredMenus.length}개의 메뉴
          {searchQuery && ` (${initialMenus.length}개 중 검색 결과)`}
        </span>
        <div className="flex gap-2">
          <ExportButton menus={filteredMenus} translate={safeTranslate} />
          <InitializeButton />
        </div>
      </div>

      {/* 테이블 */}
      <div className="rounded-md border">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead className="w-[50px]">상태</TableHead>
              <TableHead>메뉴 정보</TableHead>
              <TableHead className="w-[100px]">도메인</TableHead>
              <TableHead className="w-[200px]">담당자 1</TableHead>
              <TableHead className="w-[200px]">담당자 2</TableHead>
              {/* <TableHead className="w-[80px]">동작</TableHead> */}
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredMenus.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
                  조건에 맞는 메뉴가 없습니다.
                </TableCell>
              </TableRow>
            ) : (
              filteredMenus.map((menu) => {
                const domainUsers = getFilteredUsers(menu.domain);

                return (
                  <TableRow key={menu.id}>
                    <TableCell>
                      <Switch
                        checked={menu.isActive}
                        onCheckedChange={(checked) => handleToggleActive(menu.menuPath, checked)}
                      />
                    </TableCell>

                    <TableCell>
                      <div className="space-y-1">
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{(menu as any).translatedMenuTitle || safeTranslate(menu.menuTitle)}</span>
                          <Badge variant="outline" className="text-xs">
                            {(menu as any).translatedSectionTitle || safeTranslate(menu.sectionTitle)}
                          </Badge>
                          {menu.menuGroup && (
                            <Badge variant="secondary" className="text-xs">
                              {(menu as any).translatedMenuGroup || safeTranslate(menu.menuGroup)}
                            </Badge>
                          )}
                        </div>
                        <div className="text-xs text-muted-foreground font-mono">
                          {menu.menuPath}
                        </div>
                        {menu.menuDescription && (
                          <div className="text-xs text-muted-foreground">
                            {(menu as any).translatedMenuDescription || safeTranslate(menu.menuDescription)}
                          </div>
                        )}
                      </div>
                    </TableCell>

                    <TableCell>
                      <Badge
                        variant={menu.domain === "evcp" ? "default" : "secondary"}
                        className="text-xs"
                      >
                        {menu.domain.toUpperCase()}
                      </Badge>
                    </TableCell>

                    <TableCell>
                      <ManagerSelect
                        menuPath={menu.menuPath}
                        currentManagerId={menu.manager1Id}
                        users={domainUsers}
                        placeholder="담당자 1 선택"
                        otherManagerId={menu.manager2Id}
                        type="manager1"
                      />
                    </TableCell>

                    <TableCell>
                      <ManagerSelect
                        menuPath={menu.menuPath}
                        currentManagerId={menu.manager2Id}
                        users={domainUsers}
                        placeholder="담당자 2 선택"
                        otherManagerId={menu.manager1Id}
                        type="manager2"
                      />
                    </TableCell>

                    {/* <TableCell>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => window.open(menu.menuPath, '_blank')}
                      >
                        <ExternalLink className="h-3 w-3" />
                      </Button>
                    </TableCell> */}
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}