"use client";

import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { toast } from "sonner";
import { showErrorToast } from "@/lib/utils/toastUtils";
import { Plus, Search, Edit, Trash2, Eye, RotateCcw, SortAsc, SortDesc } from "lucide-react";
import { useWebTypes } from "@/hooks/admin/useWebTypes";
import Link from "next/link";

export default function WebTypesManagePage() {
  const [searchTerm, setSearchTerm] = useState("");
  const [categoryFilter, setCategoryFilter] = useState<string>("all");
  const [activeFilter, setActiveFilter] = useState<string>("Y");
  const [sortField, setSortField] = useState<string>("sort_order");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");

  // 웹타입 데이터 조회
  const { webTypes, isLoading, error, deleteWebType, isDeleting, deleteError, refetch } = useWebTypes({
    active: activeFilter === "all" ? undefined : activeFilter,
    search: searchTerm || undefined,
    category: categoryFilter === "all" ? undefined : categoryFilter,
  });

  // 카테고리 목록 생성
  const categories = useMemo(() => {
    const uniqueCategories = Array.from(new Set(webTypes.map((wt) => wt.category).filter(Boolean)));
    return uniqueCategories.sort();
  }, [webTypes]);

  // 필터링 및 정렬된 데이터
  const filteredAndSortedWebTypes = useMemo(() => {
    let filtered = [...webTypes];

    // 정렬
    filtered.sort((a, b) => {
      let aValue: any = a[sortField as keyof typeof a];
      let bValue: any = b[sortField as keyof typeof b];

      // 숫자 필드 처리
      if (sortField === "sort_order") {
        aValue = aValue || 0;
        bValue = bValue || 0;
      }

      // 문자열 필드 처리
      if (typeof aValue === "string") {
        aValue = aValue.toLowerCase();
      }
      if (typeof bValue === "string") {
        bValue = bValue.toLowerCase();
      }

      if (aValue < bValue) return sortDirection === "asc" ? -1 : 1;
      if (aValue > bValue) return sortDirection === "asc" ? 1 : -1;
      return 0;
    });

    return filtered;
  }, [webTypes, sortField, sortDirection]);

  // 정렬 변경 핸들러
  const handleSort = (field: string) => {
    if (sortField === field) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      setSortDirection("asc");
    }
  };

  // 삭제 핸들러
  const handleDelete = async (webType: string, typeName: string) => {
    try {
      await deleteWebType(webType);
      toast.success(`웹타입 '${typeName}'이 삭제되었습니다.`);
    } catch (error) {
      showErrorToast("웹타입 삭제에 실패했습니다", error, { guidance: "잠시 후 다시 시도해 주세요." });
    }
  };

  // 필터 초기화
  const resetFilters = () => {
    setSearchTerm("");
    setCategoryFilter("all");
    setActiveFilter("Y");
    setSortField("sort_order");
    setSortDirection("asc");
  };

  return (
    <div className="space-y-6">
      {/* 페이지 헤더 */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold">웹타입 관리</h1>
          <p className="text-sm text-muted-foreground">화면관리에서 사용할 웹타입들을 관리합니다</p>
        </div>
        <Link href="/admin/standards/new">
          <Button className="w-full sm:w-auto">
            <Plus className="mr-2 h-4 w-4" />새 웹타입 추가
          </Button>
        </Link>
      </div>

      {/* 에러 상태 */}
      {error && (
        <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4">
          <p className="text-sm font-semibold text-destructive">웹타입 목록을 불러오는데 실패했습니다.</p>
          <Button onClick={() => refetch()} variant="outline" size="sm" className="mt-2">
            다시 시도
          </Button>
        </div>
      )}

      {/* 검색 툴바 */}
      <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
          <div className="relative w-full sm:w-[300px]">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              placeholder="웹타입명, 설명 검색..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="h-10 pl-10 text-sm"
            />
          </div>

          <Select value={categoryFilter} onValueChange={setCategoryFilter}>
            <SelectTrigger className="h-10 w-full sm:w-[160px]">
              <SelectValue placeholder="카테고리 선택" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체 카테고리</SelectItem>
              {categories.map((category) => (
                <SelectItem key={category} value={category}>
                  {category}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <Select value={activeFilter} onValueChange={setActiveFilter}>
            <SelectTrigger className="h-10 w-full sm:w-[160px]">
              <SelectValue placeholder="상태 선택" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">전체</SelectItem>
              <SelectItem value="Y">활성화</SelectItem>
              <SelectItem value="N">비활성화</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <Button variant="outline" onClick={resetFilters} className="h-10 w-full sm:w-auto">
          <RotateCcw className="mr-2 h-4 w-4" />
          초기화
        </Button>
      </div>

      {/* 결과 수 */}
      <div className="text-sm text-muted-foreground">
        총 <span className="font-semibold text-foreground">{filteredAndSortedWebTypes.length}</span>개의 웹타입
      </div>

      {/* 삭제 에러 */}
      {deleteError && (
        <div className="rounded-lg border border-destructive/50 bg-destructive/10 p-4">
          <p className="text-sm text-destructive">
            삭제 중 오류가 발생했습니다: {deleteError instanceof Error ? deleteError.message : "알 수 없는 오류"}
          </p>
        </div>
      )}

      {isLoading ? (
        <>
          {/* 데스크톱 스켈레톤 */}
          <div className="hidden rounded-lg border bg-card shadow-sm lg:block">
            <Table>
              <TableHeader>
                <TableRow className="border-b bg-muted/50 hover:bg-muted/50">
                  <TableHead className="h-12 text-sm font-semibold">순서</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">웹타입 코드</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">웹타입명</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">카테고리</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">설명</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">상태</TableHead>
                  <TableHead className="h-12 text-sm font-semibold">최종 수정일</TableHead>
                  <TableHead className="h-12 text-sm font-semibold text-center">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {Array.from({ length: 6 }).map((_, i) => (
                  <TableRow key={i} className="border-b">
                    <TableCell className="h-16"><div className="h-4 w-8 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 w-20 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 w-24 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 w-16 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 w-32 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 w-12 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="h-4 w-20 animate-pulse rounded bg-muted"></div></TableCell>
                    <TableCell className="h-16"><div className="mx-auto h-4 w-16 animate-pulse rounded bg-muted"></div></TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>
          {/* 모바일 스켈레톤 */}
          <div className="grid gap-4 sm:grid-cols-2 lg:hidden">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="rounded-lg border bg-card p-4 shadow-sm">
                <div className="mb-4 space-y-2">
                  <div className="h-5 w-32 animate-pulse rounded bg-muted"></div>
                  <div className="h-4 w-24 animate-pulse rounded bg-muted"></div>
                </div>
                <div className="space-y-2 border-t pt-4">
                  {Array.from({ length: 4 }).map((_, j) => (
                    <div key={j} className="flex justify-between">
                      <div className="h-4 w-16 animate-pulse rounded bg-muted"></div>
                      <div className="h-4 w-24 animate-pulse rounded bg-muted"></div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </>
      ) : filteredAndSortedWebTypes.length === 0 ? (
        <div className="flex h-32 items-center justify-center rounded-lg border bg-card text-sm text-muted-foreground">
          조건에 맞는 웹타입이 없습니다.
        </div>
      ) : (
        <>
          {/* 데스크톱 테이블 */}
          <div className="hidden rounded-lg border bg-card shadow-sm lg:block">
            <Table>
              <TableHeader>
                <TableRow className="border-b bg-muted/50 hover:bg-muted/50">
                  <TableHead className="h-12 cursor-pointer text-sm font-semibold hover:bg-muted/50" onClick={() => handleSort("sort_order")}>
                    <div className="flex items-center gap-2">
                      순서
                      {sortField === "sort_order" &&
                        (sortDirection === "asc" ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />)}
                    </div>
                  </TableHead>
                  <TableHead className="h-12 cursor-pointer text-sm font-semibold hover:bg-muted/50" onClick={() => handleSort("web_type")}>
                    <div className="flex items-center gap-2">
                      웹타입 코드
                      {sortField === "web_type" &&
                        (sortDirection === "asc" ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />)}
                    </div>
                  </TableHead>
                  <TableHead className="h-12 cursor-pointer text-sm font-semibold hover:bg-muted/50" onClick={() => handleSort("type_name")}>
                    <div className="flex items-center gap-2">
                      웹타입명
                      {sortField === "type_name" &&
                        (sortDirection === "asc" ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />)}
                    </div>
                  </TableHead>
                  <TableHead className="h-12 cursor-pointer text-sm font-semibold hover:bg-muted/50" onClick={() => handleSort("category")}>
                    <div className="flex items-center gap-2">
                      카테고리
                      {sortField === "category" &&
                        (sortDirection === "asc" ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />)}
                    </div>
                  </TableHead>
                  <TableHead className="h-12 text-sm font-semibold">설명</TableHead>
                  <TableHead className="h-12 cursor-pointer text-sm font-semibold hover:bg-muted/50" onClick={() => handleSort("is_active")}>
                    <div className="flex items-center gap-2">
                      상태
                      {sortField === "is_active" &&
                        (sortDirection === "asc" ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />)}
                    </div>
                  </TableHead>
                  <TableHead className="h-12 cursor-pointer text-sm font-semibold hover:bg-muted/50" onClick={() => handleSort("updated_date")}>
                    <div className="flex items-center gap-2">
                      최종 수정일
                      {sortField === "updated_date" &&
                        (sortDirection === "asc" ? <SortAsc className="h-4 w-4" /> : <SortDesc className="h-4 w-4" />)}
                    </div>
                  </TableHead>
                  <TableHead className="h-12 text-center text-sm font-semibold">작업</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {filteredAndSortedWebTypes.map((webType) => (
                  <TableRow key={webType.web_type} className="border-b transition-colors hover:bg-muted/50">
                    <TableCell className="h-16 font-mono text-sm">{webType.sort_order || 0}</TableCell>
                    <TableCell className="h-16 font-mono text-sm">{webType.web_type}</TableCell>
                    <TableCell className="h-16 text-sm">
                      <div className="font-medium">{webType.type_name}</div>
                      {webType.type_name_eng && (
                        <div className="text-xs text-muted-foreground">{webType.type_name_eng}</div>
                      )}
                    </TableCell>
                    <TableCell className="h-16 text-sm">
                      <Badge variant="secondary">{webType.category}</Badge>
                    </TableCell>
                    <TableCell className="h-16 max-w-xs truncate text-sm">{webType.description || "-"}</TableCell>
                    <TableCell className="h-16 text-sm">
                      <Badge variant={webType.is_active === "Y" ? "default" : "secondary"}>
                        {webType.is_active === "Y" ? "활성화" : "비활성화"}
                      </Badge>
                    </TableCell>
                    <TableCell className="h-16 text-sm text-muted-foreground">
                      {webType.updated_date ? new Date(webType.updated_date).toLocaleDateString("ko-KR") : "-"}
                    </TableCell>
                    <TableCell className="h-16 text-sm">
                      <div className="flex items-center justify-center gap-1">
                        <Link href={`/admin/standards/${webType.web_type}`}>
                          <Button variant="ghost" size="sm">
                            <Eye className="h-4 w-4" />
                          </Button>
                        </Link>
                        <Link href={`/admin/standards/${webType.web_type}/edit`}>
                          <Button variant="ghost" size="sm">
                            <Edit className="h-4 w-4" />
                          </Button>
                        </Link>
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button variant="ghost" size="sm">
                              <Trash2 className="h-4 w-4 text-destructive" />
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>웹타입 삭제</AlertDialogTitle>
                              <AlertDialogDescription>
                                '{webType.type_name}' 웹타입을 삭제하시겠습니까?
                                <br />이 작업은 되돌릴 수 없습니다.
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>취소</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => handleDelete(webType.web_type, webType.type_name)}
                                disabled={isDeleting}
                                className="bg-destructive hover:bg-destructive/90"
                              >
                                {isDeleting ? "삭제 중..." : "삭제"}
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </div>

          {/* 모바일 카드 */}
          <div className="grid gap-4 sm:grid-cols-2 lg:hidden">
            {filteredAndSortedWebTypes.map((webType) => (
              <div
                key={webType.web_type}
                className="rounded-lg border bg-card p-4 shadow-sm transition-colors hover:bg-muted/50"
              >
                <div className="mb-3 flex items-start justify-between">
                  <div className="flex-1 min-w-0">
                    <h3 className="text-base font-semibold">{webType.type_name}</h3>
                    {webType.type_name_eng && (
                      <p className="text-xs text-muted-foreground">{webType.type_name_eng}</p>
                    )}
                    <p className="mt-0.5 font-mono text-xs text-muted-foreground">{webType.web_type}</p>
                  </div>
                  <Badge variant={webType.is_active === "Y" ? "default" : "secondary"} className="ml-2 shrink-0">
                    {webType.is_active === "Y" ? "활성화" : "비활성화"}
                  </Badge>
                </div>
                <div className="space-y-1.5 border-t pt-3">
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">카테고리</span>
                    <Badge variant="secondary">{webType.category}</Badge>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">순서</span>
                    <span className="font-medium">{webType.sort_order || 0}</span>
                  </div>
                  {webType.description && (
                    <div className="flex justify-between gap-2 text-sm">
                      <span className="shrink-0 text-muted-foreground">설명</span>
                      <span className="truncate text-right">{webType.description}</span>
                    </div>
                  )}
                  <div className="flex justify-between text-sm">
                    <span className="text-muted-foreground">수정일</span>
                    <span className="text-xs">
                      {webType.updated_date ? new Date(webType.updated_date).toLocaleDateString("ko-KR") : "-"}
                    </span>
                  </div>
                </div>
                <div className="mt-3 flex gap-2 border-t pt-3">
                  <Link href={`/admin/standards/${webType.web_type}`} className="flex-1">
                    <Button variant="outline" size="sm" className="h-9 w-full gap-2 text-sm">
                      <Eye className="h-4 w-4" />
                      보기
                    </Button>
                  </Link>
                  <Link href={`/admin/standards/${webType.web_type}/edit`} className="flex-1">
                    <Button variant="outline" size="sm" className="h-9 w-full gap-2 text-sm">
                      <Edit className="h-4 w-4" />
                      수정
                    </Button>
                  </Link>
                  <AlertDialog>
                    <AlertDialogTrigger asChild>
                      <Button variant="outline" size="sm" className="h-9 w-9 p-0 text-destructive hover:text-destructive">
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </AlertDialogTrigger>
                    <AlertDialogContent>
                      <AlertDialogHeader>
                        <AlertDialogTitle>웹타입 삭제</AlertDialogTitle>
                        <AlertDialogDescription>
                          '{webType.type_name}' 웹타입을 삭제하시겠습니까?
                          <br />이 작업은 되돌릴 수 없습니다.
                        </AlertDialogDescription>
                      </AlertDialogHeader>
                      <AlertDialogFooter>
                        <AlertDialogCancel>취소</AlertDialogCancel>
                        <AlertDialogAction
                          onClick={() => handleDelete(webType.web_type, webType.type_name)}
                          disabled={isDeleting}
                          className="bg-destructive hover:bg-destructive/90"
                        >
                          {isDeleting ? "삭제 중..." : "삭제"}
                        </AlertDialogAction>
                      </AlertDialogFooter>
                    </AlertDialogContent>
                  </AlertDialog>
                </div>
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  );
}
