"use client";

import React, { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { ArrowLeft, Edit, Settings, Code, Eye } from "lucide-react";
import { useWebTypes } from "@/hooks/admin/useWebTypes";
import Link from "next/link";

export default function WebTypeDetailPage() {
  const params = useParams();
  const router = useRouter();
  const webType = params.webType as string;

  const { webTypes, isLoading, error } = useWebTypes();
  const [webTypeData, setWebTypeData] = useState<any>(null);

  // 웹타입 데이터 로드
  useEffect(() => {
    if (webTypes && webType) {
      const found = webTypes.find((wt) => wt.web_type === webType);
      if (found) {
        setWebTypeData(found);
      } else {
        toast.error("웹타입을 찾을 수 없습니다.");
        router.push("/admin/standards");
      }
    }
  }, [webTypes, webType, router]);

  // JSON 포맷팅 함수
  const formatJson = (obj: any): string => {
    if (!obj || typeof obj !== "object") return "{}";
    try {
      return JSON.stringify(obj, null, 2);
    } catch {
      return "{}";
    }
  };

  // 로딩 상태
  if (isLoading) {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="text-lg">웹타입 정보를 불러오는 중...</div>
      </div>
    );
  }

  // 에러 상태
  if (error) {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="text-center">
          <div className="mb-2 text-lg text-destructive">웹타입 정보를 불러오는데 실패했습니다.</div>
          <Link href="/admin/standards">
            <Button variant="outline">목록으로 돌아가기</Button>
          </Link>
        </div>
      </div>
    );
  }

  // 웹타입을 찾지 못한 경우
  if (!webTypeData) {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="text-center">
          <div className="text-muted-foreground mb-2 text-lg">웹타입을 찾을 수 없습니다.</div>
          <Link href="/admin/standards">
            <Button variant="outline">목록으로 돌아가기</Button>
          </Link>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-muted">
      <div className="w-full max-w-none px-4 py-8 space-y-8">
      {/* 헤더 */}
      <div className="mb-6 flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Link href="/admin/standards">
            <Button variant="ghost" size="sm">
              <ArrowLeft className="mr-2 h-4 w-4" />
              목록으로
            </Button>
          </Link>
          <div>
            <div className="flex items-center gap-3">
              <h1 className="text-3xl font-bold tracking-tight">{webTypeData.type_name}</h1>
              <Badge variant={webTypeData.is_active === "Y" ? "default" : "secondary"}>
                {webTypeData.is_active === "Y" ? "활성화" : "비활성화"}
              </Badge>
            </div>
            <div className="mt-1 flex items-center gap-4">
              <p className="text-muted-foreground font-mono">{webTypeData.web_type}</p>
              {webTypeData.type_name_eng && <p className="text-muted-foreground">{webTypeData.type_name_eng}</p>}
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <Link href={`/admin/standards/${webType}/edit`}>
            <Button>
              <Edit className="mr-2 h-4 w-4" />
              편집
            </Button>
          </Link>
        </div>
      </div>

      <Tabs defaultValue="overview" className="space-y-8">
        <TabsList>
          <TabsTrigger value="overview" className="flex items-center gap-2">
            <Eye className="h-4 w-4" />
            개요
          </TabsTrigger>
          <TabsTrigger value="config" className="flex items-center gap-2">
            <Settings className="h-4 w-4" />
            설정
          </TabsTrigger>
          <TabsTrigger value="json" className="flex items-center gap-2">
            <Code className="h-4 w-4" />
            JSON 데이터
          </TabsTrigger>
        </TabsList>

        {/* 개요 탭 */}
        <TabsContent value="overview" className="space-y-8">
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            {/* 기본 정보 */}
            <Card>
              <CardHeader>
                <CardTitle>기본 정보</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">웹타입 코드</dt>
                  <dd className="font-mono text-lg">{webTypeData.web_type}</dd>
                </div>
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">웹타입명</dt>
                  <dd className="text-lg">{webTypeData.type_name}</dd>
                </div>
                {webTypeData.type_name_eng && (
                  <div>
                    <dt className="text-muted-foreground text-sm font-medium">영문명</dt>
                    <dd className="text-lg">{webTypeData.type_name_eng}</dd>
                  </div>
                )}
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">카테고리</dt>
                  <dd>
                    <Badge variant="secondary">{webTypeData.category}</Badge>
                  </dd>
                </div>
                {webTypeData.description && (
                  <div>
                    <dt className="text-muted-foreground text-sm font-medium">설명</dt>
                    <dd className="text-muted-foreground text-sm">{webTypeData.description}</dd>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 메타데이터 */}
            <Card>
              <CardHeader>
                <CardTitle>메타데이터</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">정렬 순서</dt>
                  <dd className="text-lg">{webTypeData.sort_order || 0}</dd>
                </div>
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">상태</dt>
                  <dd>
                    <Badge variant={webTypeData.is_active === "Y" ? "default" : "secondary"}>
                      {webTypeData.is_active === "Y" ? "활성화" : "비활성화"}
                    </Badge>
                  </dd>
                </div>
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">생성일</dt>
                  <dd className="text-sm">
                    {webTypeData.created_date ? new Date(webTypeData.created_date).toLocaleString("ko-KR") : "-"}
                  </dd>
                </div>
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">생성자</dt>
                  <dd className="text-sm">{webTypeData.created_by || "-"}</dd>
                </div>
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">최종 수정일</dt>
                  <dd className="text-sm">
                    {webTypeData.updated_date ? new Date(webTypeData.updated_date).toLocaleString("ko-KR") : "-"}
                  </dd>
                </div>
                <div>
                  <dt className="text-muted-foreground text-sm font-medium">수정자</dt>
                  <dd className="text-sm">{webTypeData.updated_by || "-"}</dd>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* 설정 탭 */}
        <TabsContent value="config" className="space-y-8">
          <div className="grid grid-cols-1 gap-6 md:grid-cols-2">
            {/* 기본 설정 */}
            <Card>
              <CardHeader>
                <CardTitle>기본 설정</CardTitle>
                <CardDescription>웹타입의 기본 동작 설정입니다.</CardDescription>
              </CardHeader>
              <CardContent>
                <pre className="bg-muted overflow-auto rounded-md p-4 text-xs">
                  {formatJson(webTypeData.default_config)}
                </pre>
              </CardContent>
            </Card>

            {/* 유효성 검사 규칙 */}
            <Card>
              <CardHeader>
                <CardTitle>유효성 검사 규칙</CardTitle>
                <CardDescription>입력값 검증을 위한 규칙입니다.</CardDescription>
              </CardHeader>
              <CardContent>
                <pre className="bg-muted overflow-auto rounded-md p-4 text-xs">
                  {formatJson(webTypeData.validation_rules)}
                </pre>
              </CardContent>
            </Card>

            {/* 기본 스타일 */}
            <Card>
              <CardHeader>
                <CardTitle>기본 스타일</CardTitle>
                <CardDescription>웹타입의 기본 스타일 설정입니다.</CardDescription>
              </CardHeader>
              <CardContent>
                <pre className="bg-muted overflow-auto rounded-md p-4 text-xs">
                  {formatJson(webTypeData.default_style)}
                </pre>
              </CardContent>
            </Card>

            {/* HTML 입력 속성 */}
            <Card>
              <CardHeader>
                <CardTitle>HTML 입력 속성</CardTitle>
                <CardDescription>HTML 요소에 적용될 기본 속성입니다.</CardDescription>
              </CardHeader>
              <CardContent>
                <pre className="bg-muted overflow-auto rounded-md p-4 text-xs">
                  {formatJson(webTypeData.input_properties)}
                </pre>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* JSON 데이터 탭 */}
        <TabsContent value="json" className="space-y-8">
          <Card>
            <CardHeader>
              <CardTitle>전체 JSON 데이터</CardTitle>
              <CardDescription>웹타입의 모든 데이터를 JSON 형식으로 확인할 수 있습니다.</CardDescription>
            </CardHeader>
            <CardContent>
              <pre className="bg-muted max-h-96 overflow-auto rounded-md p-4 text-xs">{formatJson(webTypeData)}</pre>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
      </div>
    </div>
  );
}
