"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Plus, ArrowLeft, ArrowRight, CheckCircle, Circle } from "lucide-react";
import ScreenList from "@/components/screen/ScreenList";
import ScreenDesigner from "@/components/screen/ScreenDesigner";
import TemplateManager from "@/components/screen/TemplateManager";
import { ScreenDefinition } from "@/types/screen";

// 단계별 진행을 위한 타입 정의
type Step = "list" | "design" | "template";

export default function ScreenManagementPage() {
  const [currentStep, setCurrentStep] = useState<Step>("list");
  const [selectedScreen, setSelectedScreen] = useState<ScreenDefinition | null>(null);
  const [stepHistory, setStepHistory] = useState<Step[]>(["list"]);

  // 단계별 제목과 설명
  const stepConfig = {
    list: {
      title: "화면 목록 관리",
      description: "생성된 화면들을 확인하고 관리하세요",
      icon: "📋",
    },
    design: {
      title: "화면 설계",
      description: "드래그앤드롭으로 화면을 설계하세요",
      icon: "🎨",
    },
    template: {
      title: "템플릿 관리",
      description: "화면 템플릿을 관리하고 재사용하세요",
      icon: "📝",
    },
  };

  // 다음 단계로 이동
  const goToNextStep = (nextStep: Step) => {
    setStepHistory((prev) => [...prev, nextStep]);
    setCurrentStep(nextStep);
  };

  // 이전 단계로 이동
  const goToPreviousStep = () => {
    if (stepHistory.length > 1) {
      const newHistory = stepHistory.slice(0, -1);
      const previousStep = newHistory[newHistory.length - 1];
      setStepHistory(newHistory);
      setCurrentStep(previousStep);
    }
  };

  // 특정 단계로 이동
  const goToStep = (step: Step) => {
    setCurrentStep(step);
    // 해당 단계까지의 히스토리만 유지
    const stepIndex = stepHistory.findIndex((s) => s === step);
    if (stepIndex !== -1) {
      setStepHistory(stepHistory.slice(0, stepIndex + 1));
    }
  };

  // 단계별 진행 상태 확인
  const isStepCompleted = (step: Step) => {
    return stepHistory.includes(step);
  };

  // 현재 단계가 마지막 단계인지 확인
  const isLastStep = currentStep === "template";

  return (
    <div className="flex h-full w-full flex-col">
      {/* 페이지 헤더 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-900">화면관리 시스템</h1>
          <p className="mt-2 text-gray-600">단계별로 화면을 관리하고 설계하세요</p>
        </div>
        <div className="text-sm text-gray-500">{stepConfig[currentStep].description}</div>
      </div>

      {/* 단계별 진행 표시 */}
      <div className="border-b bg-white p-4">
        <div className="flex items-center justify-between">
          {Object.entries(stepConfig).map(([step, config], index) => (
            <div key={step} className="flex items-center">
              <div className="flex flex-col items-center">
                <button
                  onClick={() => goToStep(step as Step)}
                  className={`flex h-12 w-12 items-center justify-center rounded-full border-2 transition-all ${
                    currentStep === step
                      ? "border-blue-600 bg-blue-600 text-white"
                      : isStepCompleted(step as Step)
                        ? "border-green-500 bg-green-500 text-white"
                        : "border-gray-300 bg-white text-gray-400"
                  } ${isStepCompleted(step as Step) ? "cursor-pointer hover:bg-green-600" : ""}`}
                >
                  {isStepCompleted(step as Step) && currentStep !== step ? (
                    <CheckCircle className="h-6 w-6" />
                  ) : (
                    <span className="text-lg">{config.icon}</span>
                  )}
                </button>
                <div className="mt-2 text-center">
                  <div
                    className={`text-sm font-medium ${
                      currentStep === step
                        ? "text-blue-600"
                        : isStepCompleted(step as Step)
                          ? "text-green-600"
                          : "text-gray-500"
                    }`}
                  >
                    {config.title}
                  </div>
                </div>
              </div>
              {index < Object.keys(stepConfig).length - 1 && (
                <div className={`mx-4 h-0.5 w-16 ${isStepCompleted(step as Step) ? "bg-green-500" : "bg-gray-300"}`} />
              )}
            </div>
          ))}
        </div>
      </div>

      {/* 단계별 내용 */}
      <div className="flex-1 overflow-hidden">
        {/* 화면 목록 단계 */}
        {currentStep === "list" && (
          <div className="h-full p-6">
            <div className="mb-6 flex items-center justify-between">
              <h2 className="text-2xl font-bold">{stepConfig.list.title}</h2>
              <Button className="bg-blue-600 hover:bg-blue-700" onClick={() => goToNextStep("design")}>
                화면 설계하기 <ArrowRight className="ml-2 h-4 w-4" />
              </Button>
            </div>
            <ScreenList
              onScreenSelect={setSelectedScreen}
              selectedScreen={selectedScreen}
              onDesignScreen={(screen) => {
                setSelectedScreen(screen);
                goToNextStep("design");
              }}
            />
          </div>
        )}

        {/* 화면 설계 단계 */}
        {currentStep === "design" && (
          <div className="h-full">
            <ScreenDesigner selectedScreen={selectedScreen} onBackToList={() => goToStep("list")} />
          </div>
        )}

        {/* 템플릿 관리 단계 */}
        {currentStep === "template" && (
          <div className="h-full p-6">
            <div className="mb-6 flex items-center justify-between">
              <h2 className="text-2xl font-bold">{stepConfig.template.title}</h2>
              <div className="flex gap-2">
                <Button variant="outline" onClick={goToPreviousStep}>
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  이전 단계
                </Button>
                <Button className="bg-blue-600 hover:bg-blue-700" onClick={() => goToStep("list")}>
                  목록으로 돌아가기
                </Button>
              </div>
            </div>
            <TemplateManager selectedScreen={selectedScreen} onBackToList={() => goToStep("list")} />
          </div>
        )}
      </div>
    </div>
  );
}
