import { useState, useEffect } from "react";
import { useNavigate, Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { motion, AnimatePresence } from "framer-motion";
import { Home, ChevronRight } from "lucide-react";
import AdminLayout from "@/components/pc/admin/layout/Layout";
import { useAdminAuth } from "@/hooks/pc/admin";
import * as categoriesApi from "@/api/admin/categories";
import CategorySelector from "@/components/pc/admin/schedule/CategorySelector";
import YouTubeForm from "./YouTubeForm";
import XForm from "./XForm";
import ConcertForm from "./concert";
import VarietyForm from "./VarietyForm";
import EventForm from "./event";

// 애니메이션 variants
const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.1,
    },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.4, ease: "easeOut" },
  },
};

/**
 * 일정 추가 페이지 (카테고리별 폼 분기)
 */
function ScheduleFormPage() {
  const navigate = useNavigate();
  const { user, isAuthenticated } = useAdminAuth();

  const [selectedCategory, setSelectedCategory] = useState(null);
  const [isInitialLoad, setIsInitialLoad] = useState(true);

  // 카테고리 로드 (React Query)
  const { data: categories = [], isLoading: loading } = useQuery({
    queryKey: ["scheduleCategories"],
    queryFn: categoriesApi.getCategories,
    enabled: isAuthenticated,
    staleTime: 10 * 60 * 1000,
    onSuccess: (data) => {
      if (data.length > 0 && !selectedCategory) {
        setSelectedCategory(data[0].id);
      }
    },
  });

  // 카테고리 로드 시 기본값 설정
  useEffect(() => {
    if (categories.length > 0 && !selectedCategory) {
      setSelectedCategory(categories[0].id);
    }
  }, [categories, selectedCategory]);

  // 카테고리에 따른 폼 렌더링
  const renderForm = () => {
    const selectedCategoryName = categories.find(c => c.id === selectedCategory)?.name;

    switch (selectedCategoryName) {
      case '유튜브':
        return <YouTubeForm />;

      case 'X':
        return <XForm />;

      case '콘서트':
        return <ConcertForm />;

      case '예능':
        return <VarietyForm />;

      case '행사':
        return <EventForm />;

      // 다른 카테고리는 기존 폼으로 리다이렉트
      default:
        return (
          <div className="bg-white rounded-2xl shadow-sm p-8 text-center">
            <p className="text-gray-500 mb-4">
              이 카테고리는 아직 전용 폼이 없습니다.
            </p>
            <button
              onClick={() => navigate(`/admin/schedule/new-legacy?category=${selectedCategory}`)}
              className="px-6 py-3 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors"
            >
              기존 폼으로 추가하기
            </button>
          </div>
        );
    }
  };

  if (loading) {
    return (
      <AdminLayout user={user}>
        <div className="flex items-center justify-center min-h-[400px]">
          <div className="w-8 h-8 border-4 border-primary border-t-transparent rounded-full animate-spin" />
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout user={user}>
      <motion.div
        className="max-w-4xl mx-auto px-6 py-8"
        variants={containerVariants}
        initial="hidden"
        animate="visible"
      >
        {/* 브레드크럼 */}
        <motion.div
          variants={itemVariants}
          className="flex items-center gap-2 text-sm text-gray-400 mb-8"
        >
          <Link
            to="/admin/dashboard"
            className="hover:text-primary transition-colors"
          >
            <Home size={16} />
          </Link>
          <ChevronRight size={14} />
          <Link
            to="/admin/schedule"
            className="hover:text-primary transition-colors"
          >
            일정 관리
          </Link>
          <ChevronRight size={14} />
          <span className="text-gray-700">일정 추가</span>
        </motion.div>

        {/* 타이틀 */}
        <motion.div variants={itemVariants} className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">일정 추가</h1>
          <p className="text-gray-500">카테고리를 선택하고 일정을 등록하세요</p>
        </motion.div>

        {/* 카테고리 선택 */}
        <motion.div variants={itemVariants} className="mb-6">
          <CategorySelector
            categories={categories}
            selectedId={selectedCategory}
            onChange={(id) => {
              setSelectedCategory(id);
              setIsInitialLoad(false);
            }}
          />
        </motion.div>

        {/* 카테고리별 폼 */}
        <AnimatePresence mode="wait">
          <motion.div
            key={selectedCategory}
            initial={{ opacity: 0, y: 10 }}
            animate={{
              opacity: 1,
              y: 0,
              transition: {
                duration: isInitialLoad ? 0.4 : 0.15,
                ease: "easeOut",
                delay: isInitialLoad ? 0.3 : 0,
              },
            }}
            exit={{ opacity: 0, y: -10, transition: { duration: 0.1 } }}
          >
            {renderForm()}
          </motion.div>
        </AnimatePresence>
      </motion.div>
    </AdminLayout>
  );
}

export default ScheduleFormPage;
