"use client";

import React, { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import {
  ComponentData,
  WebType,
  ButtonActionType,
  WidgetComponent,
  isWidgetComponent,
  isWebType,
  isButtonActionType,
  ynToBoolean,
  booleanToYN,
} from "@/types";

export default function SimpleTypeSafetyTest() {
  const [testResults, setTestResults] = useState<
    Array<{ name: string; status: "pending" | "passed" | "failed"; message?: string }>
  >([]);
  const [isRunning, setIsRunning] = useState(false);

  const addResult = (name: string, status: "passed" | "failed", message?: string) => {
    setTestResults((prev) => [...prev, { name, status, message }]);
  };

  const runSimpleTests = () => {
    setIsRunning(true);
    setTestResults([]);

    try {
      // Test 1: WebType 검증
      const validWebTypes = ["text", "number", "date", "select", "checkbox"];
      const invalidWebTypes = ["text_area", "VARCHAR", "submit"];

      let webTypeTestPassed = true;
      validWebTypes.forEach((type) => {
        if (!isWebType(type)) webTypeTestPassed = false;
      });
      invalidWebTypes.forEach((type) => {
        if (isWebType(type as any)) webTypeTestPassed = false;
      });

      addResult(
        "WebType 타입 검증",
        webTypeTestPassed ? "passed" : "failed",
        webTypeTestPassed ? "모든 WebType 검증 통과" : "일부 WebType 검증 실패",
      );

      // Test 2: ButtonActionType 검증
      const validActions: ButtonActionType[] = ["save", "cancel", "delete", "edit"];
      const invalidActions = ["insert", "update", ""];

      let buttonActionTestPassed = true;
      validActions.forEach((action) => {
        if (!isButtonActionType(action)) buttonActionTestPassed = false;
      });
      invalidActions.forEach((action) => {
        if (isButtonActionType(action as any)) buttonActionTestPassed = false;
      });

      addResult(
        "ButtonActionType 검증",
        buttonActionTestPassed ? "passed" : "failed",
        buttonActionTestPassed ? "모든 ButtonActionType 검증 통과" : "일부 ButtonActionType 검증 실패",
      );

      // Test 3: Y/N ↔ boolean 변환
      const ynTests = [
        { input: "Y", expected: true },
        { input: "N", expected: false },
        { input: "", expected: false },
        { input: undefined, expected: false },
      ];

      let ynTestPassed = true;
      ynTests.forEach(({ input, expected }) => {
        if (ynToBoolean(input) !== expected) ynTestPassed = false;
      });

      if (booleanToYN(true) !== "Y" || booleanToYN(false) !== "N") ynTestPassed = false;

      addResult(
        "Y/N ↔ boolean 변환",
        ynTestPassed ? "passed" : "failed",
        ynTestPassed ? "모든 Y/N 변환 테스트 통과" : "Y/N 변환 테스트 실패",
      );

      // Test 4: 컴포넌트 타입 가드
      const testWidget: WidgetComponent = {
        id: "test-widget",
        type: "widget",
        widgetType: "text",
        position: { x: 0, y: 0 },
        size: { width: 200, height: 40 },
        label: "테스트",
        webTypeConfig: {},
      };

      const testContainer = {
        id: "test-container",
        type: "container",
        position: { x: 0, y: 0 },
        size: { width: 400, height: 300 },
        children: [],
      };

      let typeGuardTestPassed = true;
      if (!isWidgetComponent(testWidget)) typeGuardTestPassed = false;
      if (isWidgetComponent(testContainer)) typeGuardTestPassed = false;

      addResult(
        "컴포넌트 타입 가드",
        typeGuardTestPassed ? "passed" : "failed",
        typeGuardTestPassed ? "타입 가드 모든 테스트 통과" : "타입 가드 테스트 실패",
      );

      // Test 5: 폼 데이터 처리 시뮬레이션
      const formData = {
        userName: "테스트 사용자",
        userAge: 25,
        isActive: true,
      };

      const formComponents: WidgetComponent[] = [
        {
          id: "userName",
          type: "widget",
          widgetType: "text",
          position: { x: 0, y: 0 },
          size: { width: 200, height: 40 },
          label: "사용자명",
          columnName: "user_name",
          webTypeConfig: {},
        },
        {
          id: "isActive",
          type: "widget",
          widgetType: "checkbox",
          position: { x: 0, y: 50 },
          size: { width: 200, height: 40 },
          label: "활성화",
          columnName: "is_active",
          webTypeConfig: {},
        },
      ];

      const processedData: Record<string, any> = {};
      formComponents.forEach((component) => {
        const fieldValue = formData[component.id as keyof typeof formData];
        if (fieldValue !== undefined && component.columnName) {
          switch (component.widgetType) {
            case "text":
              processedData[component.columnName] = String(fieldValue);
              break;
            case "checkbox":
              processedData[component.columnName] = booleanToYN(Boolean(fieldValue));
              break;
            default:
              processedData[component.columnName] = fieldValue;
          }
        }
      });

      let formProcessingTestPassed = true;
      if (typeof processedData.user_name !== "string") formProcessingTestPassed = false;
      if (processedData.is_active !== "Y" && processedData.is_active !== "N") formProcessingTestPassed = false;

      addResult(
        "폼 데이터 처리",
        formProcessingTestPassed ? "passed" : "failed",
        formProcessingTestPassed ? "폼 데이터 타입 안전 처리 성공" : "폼 데이터 처리 실패",
      );
    } catch (error) {
      addResult("전체 테스트", "failed", `테스트 실행 중 오류: ${error}`);
    }

    setIsRunning(false);
  };

  const passedTests = testResults.filter((test) => test.status === "passed").length;
  const totalTests = testResults.length;

  return (
    <div className="container mx-auto space-y-6 p-6">
      <div className="space-y-4 text-center">
        <h1 className="text-3xl font-bold">🧪 타입 안전성 간단 테스트</h1>
        <p className="text-muted-foreground">
          화면관리, 제어관리, 테이블타입관리 시스템의 핵심 타입 안전성을 검증합니다
        </p>

        <Button onClick={runSimpleTests} disabled={isRunning} size="lg">
          {isRunning ? "테스트 실행 중..." : "🚀 간단 테스트 실행"}
        </Button>
      </div>

      {testResults.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle>📊 테스트 결과</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="text-center">
                <div className="text-2xl font-bold">
                  {passedTests}/{totalTests} 통과
                </div>
                <div className="text-muted-foreground text-sm">
                  성공률: {totalTests > 0 ? Math.round((passedTests / totalTests) * 100) : 0}%
                </div>
              </div>

              {testResults.map((test, index) => (
                <div key={index} className="flex items-center justify-between rounded-lg border p-3">
                  <div className="flex-1">
                    <div className="font-medium">{test.name}</div>
                    {test.message && <div className="text-muted-foreground mt-1 text-sm">{test.message}</div>}
                  </div>

                  <Badge variant={test.status === "passed" ? "default" : "destructive"}>
                    {test.status === "passed" ? "통과" : "실패"}
                  </Badge>
                </div>
              ))}
            </div>

            {passedTests === totalTests && totalTests > 0 && (
              <div className="mt-4 rounded-lg border border-emerald-200 bg-emerald-50 p-4">
                <div className="font-medium text-emerald-800">🎉 모든 타입 안전성 테스트가 통과되었습니다!</div>
                <div className="mt-2 text-sm text-emerald-600">
                  화면관리, 제어관리, 테이블타입관리 시스템이 안전하게 작동합니다.
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
