import { useState, useEffect } from "react";
import { useNavigate, useParams, Link } from "react-router-dom";
import { motion } from "framer-motion";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import {
  Youtube,
  Loader2,
  Save,
  ExternalLink,
  Home,
  ChevronRight,
  Users,
  Check,
  ArrowLeft,
  Calendar,
} from "lucide-react";
import AdminLayout from "@/components/pc/admin/layout/Layout";
import Toast from "@/components/common/Toast";
import { useAdminAuth } from "@/hooks/pc/admin";
import { useToast } from "@/hooks/common";
import useAuthStore from "@/stores/useAuthStore";

// 애니메이션 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" },
  },
};

/**
 * YouTube 일정 수정 폼
 * - 기존 일정 데이터 로드
 * - 멤버 선택 수정
 */
function YouTubeEditForm() {
  const navigate = useNavigate();
  const { id } = useParams();
  const queryClient = useQueryClient();
  const { user, isAuthenticated } = useAdminAuth();
  const { toast, setToast } = useToast();

  const [saving, setSaving] = useState(false);
  const [selectedMembers, setSelectedMembers] = useState([]);
  const [videoType, setVideoType] = useState("video");
  const [isInitialized, setIsInitialized] = useState(false);

  // 일정 데이터 로드
  const { data: schedule, isLoading: scheduleLoading, isError: scheduleError } = useQuery({
    queryKey: ["schedule", id],
    queryFn: async () => {
      const token = useAuthStore.getState().token;
      const res = await fetch(`/api/schedules/${id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (!res.ok) throw new Error("일정을 찾을 수 없습니다.");
      return res.json();
    },
    enabled: isAuthenticated && !!id,
    retry: false,
  });

  // 멤버 목록 로드
  const { data: membersData = [], isLoading: membersLoading } = useQuery({
    queryKey: ["members"],
    queryFn: async () => {
      const res = await fetch("/api/members");
      if (!res.ok) throw new Error("멤버 목록을 불러올 수 없습니다.");
      return res.json();
    },
    enabled: isAuthenticated,
  });

  // 현재 멤버만 필터링
  const members = membersData.filter((m) => !m.is_former);

  // 일정 데이터 로드 후 초기값 설정
  useEffect(() => {
    if (schedule && !isInitialized) {
      // YouTube 일정인지 확인
      if (schedule.category?.id !== 2) {
        setToast({ type: "error", message: "YouTube 일정이 아닙니다." });
        navigate("/admin/schedule");
        return;
      }
      setSelectedMembers(schedule.members?.map((m) => m.id) || []);
      setVideoType(schedule.videoType || "video");
      setIsInitialized(true);
    }
  }, [schedule, isInitialized, navigate, setToast]);

  const loading = scheduleLoading || membersLoading;

  // 멤버 토글
  const toggleMember = (memberId) => {
    setSelectedMembers((prev) =>
      prev.includes(memberId)
        ? prev.filter((id) => id !== memberId)
        : [...prev, memberId]
    );
  };

  // 전체 선택/해제
  const toggleAllMembers = () => {
    if (selectedMembers.length === members.length) {
      setSelectedMembers([]);
    } else {
      setSelectedMembers(members.map((m) => m.id));
    }
  };

  // 폼 제출
  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);

    try {
      const token = useAuthStore.getState().token;

      const response = await fetch(`/api/admin/youtube/schedule/${id}`, {
        method: "PUT",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          memberIds: selectedMembers,
          videoType,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "수정에 실패했습니다.");
      }

      // 캐시 무효화
      queryClient.invalidateQueries({ queryKey: ["schedule", id] });

      sessionStorage.setItem(
        "scheduleToast",
        JSON.stringify({
          type: "success",
          message: "YouTube 일정이 수정되었습니다.",
        })
      );
      navigate("/admin/schedule");
    } catch (err) {
      setToast({
        type: "error",
        message: err.message,
      });
    } finally {
      setSaving(false);
    }
  };

  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>
    );
  }

  if (scheduleError || !schedule) {
    return (
      <AdminLayout user={user}>
        <div className="flex-1 flex items-center justify-center min-h-[calc(100vh-200px)]">
          <div className="text-center px-6">
            <motion.div
              initial={{ opacity: 0, scale: 0.5 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.5, type: "spring", stiffness: 100 }}
              className="mb-8"
            >
              <div className="w-32 h-32 mx-auto bg-gradient-to-br from-primary/10 to-primary/5 rounded-3xl flex items-center justify-center">
                <Calendar size={64} className="text-primary/40" />
              </div>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2, duration: 0.5 }}
              className="mb-8"
            >
              <h2 className="text-2xl font-bold text-gray-800 mb-3">
                일정을 찾을 수 없습니다
              </h2>
              <p className="text-gray-500 leading-relaxed">
                요청하신 일정이 존재하지 않거나 삭제되었을 수 있습니다.
              </p>
            </motion.div>
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4, duration: 0.5 }}
              className="flex justify-center gap-4"
            >
              <button
                onClick={() => window.history.back()}
                className="flex items-center gap-2 px-6 py-3 border-2 border-primary text-primary rounded-xl font-medium hover:bg-primary hover:text-white transition-colors duration-200"
              >
                <ArrowLeft size={18} />
                이전 페이지
              </button>
              <Link
                to="/admin/schedule"
                className="flex items-center gap-2 px-6 py-3 bg-gradient-to-r from-primary to-primary-dark text-white rounded-xl font-medium hover:shadow-lg hover:shadow-primary/30 transition-all duration-200"
              >
                <Calendar size={18} />
                일정 목록
              </Link>
            </motion.div>
          </div>
        </div>
      </AdminLayout>
    );
  }

  const videoUrl = videoType === "shorts"
    ? `https://www.youtube.com/shorts/${schedule.videoId}`
    : `https://www.youtube.com/watch?v=${schedule.videoId}`;

  // 날짜 포맷팅 함수
  const formatDatetime = (dateStr, timeStr) => {
    if (!dateStr) return "";
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const dayNames = ["일", "월", "화", "수", "목", "금", "토"];
    const dayName = dayNames[date.getDay()];
    const time = timeStr ? timeStr.slice(0, 5) : "";
    return `${year}년 ${month}월 ${day}일 (${dayName}) ${time}`;
  };

  return (
    <AdminLayout user={user}>
      <Toast toast={toast} onClose={() => setToast(null)} />

      <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">YouTube 일정 수정</span>
        </motion.div>

        <form onSubmit={handleSubmit} className="space-y-6">
          {videoType === "shorts" ? (
            /* Shorts 레이아웃: 영상(왼쪽) + 정보/멤버(오른쪽) */
            <motion.div
              variants={itemVariants}
              className="bg-white rounded-2xl shadow-sm p-8"
            >
              <div className="flex gap-8">
                {/* 왼쪽: 영상 */}
                <div className="flex-shrink-0 w-96">
                  <div className="bg-black rounded-xl overflow-hidden">
                    <div className="relative aspect-[9/16]">
                      <iframe
                        src={`https://www.youtube.com/embed/${schedule.videoId}`}
                        title={schedule.title}
                        className="absolute inset-0 w-full h-full"
                        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                        allowFullScreen
                      />
                    </div>
                  </div>
                </div>

                {/* 오른쪽: 정보 + 멤버 선택 */}
                <div className="flex-1 min-w-0">
                  {/* 영상 정보 */}
                  <div className="flex items-center gap-2 mb-4">
                    <Youtube size={24} className="text-red-500" />
                    <h2 className="text-lg font-bold text-gray-900">영상 정보</h2>
                  </div>

                  <h3 className="text-base font-bold text-gray-900 mb-3 line-clamp-2">
                    {schedule.title}
                  </h3>

                  <div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-gray-600 mb-3">
                    <span>
                      <span className="text-gray-400">채널:</span>{" "}
                      {schedule.channelName}
                    </span>
                    <span>
                      <span className="text-gray-400">업로드:</span>{" "}
                      {formatDatetime(schedule.date, schedule.time)}
                    </span>
                  </div>

                  <div className="flex items-center gap-4 mb-4">
                    <div className="flex items-center gap-2">
                      <span className="text-sm text-gray-400">유형:</span>
                      <button
                        type="button"
                        onClick={() => setVideoType("video")}
                        className="px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-500 hover:bg-gray-200 transition-colors"
                      >
                        Video
                      </button>
                      <button
                        type="button"
                        onClick={() => setVideoType("shorts")}
                        className="px-3 py-1 rounded-full text-xs font-medium bg-pink-500 text-white transition-colors"
                      >
                        Shorts
                      </button>
                    </div>
                    <a
                      href={videoUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1 text-sm text-red-500 hover:text-red-600 transition-colors"
                    >
                      <ExternalLink size={14} />
                      YouTube
                    </a>
                  </div>

                  {/* 멤버 선택 */}
                  <div className="border-t border-gray-100 pt-4">
                    <div className="flex items-center justify-between mb-4">
                      <div className="flex items-center gap-2">
                        <Users size={18} className="text-primary" />
                        <h2 className="text-base font-bold text-gray-900">출연 멤버</h2>
                      </div>
                      <button
                        type="button"
                        onClick={toggleAllMembers}
                        className="text-sm text-primary hover:underline"
                      >
                        {selectedMembers.length === members.length
                          ? "전체 해제"
                          : "전체 선택"}
                      </button>
                    </div>

                    <div className="grid grid-cols-3 gap-3">
                      {members.map((member) => {
                        const isSelected = selectedMembers.includes(member.id);
                        return (
                          <button
                            key={member.id}
                            type="button"
                            onClick={() => toggleMember(member.id)}
                            className={`relative rounded-xl overflow-hidden transition-all ${
                              isSelected
                                ? "ring-2 ring-primary ring-offset-2"
                                : "hover:opacity-80"
                            }`}
                          >
                            <div className="aspect-[3/4] bg-gray-100">
                              {member.image_url ? (
                                <img
                                  src={member.image_url}
                                  alt={member.name}
                                  className="w-full h-full object-cover"
                                />
                              ) : (
                                <div className="w-full h-full flex items-center justify-center bg-gray-200">
                                  <Users size={20} className="text-gray-400" />
                                </div>
                              )}
                            </div>
                            <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-2">
                              <p className="text-white text-xs font-medium text-center">
                                {member.name}
                              </p>
                            </div>
                            {isSelected && (
                              <div className="absolute top-1.5 right-1.5 w-5 h-5 bg-primary rounded-full flex items-center justify-center">
                                <Check size={12} className="text-white" />
                              </div>
                            )}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>
            </motion.div>
          ) : (
            /* Video 레이아웃: 기존 세로 배치 */
            <>
              <motion.div
                variants={itemVariants}
                className="bg-white rounded-2xl shadow-sm p-8"
              >
                <div className="flex items-center gap-2 mb-6">
                  <Youtube size={24} className="text-red-500" />
                  <h2 className="text-lg font-bold text-gray-900">영상 정보</h2>
                </div>

                <div className="w-full bg-black rounded-xl overflow-hidden mb-6">
                  <div className="relative aspect-video">
                    <iframe
                      src={`https://www.youtube.com/embed/${schedule.videoId}`}
                      title={schedule.title}
                      className="absolute inset-0 w-full h-full"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowFullScreen
                    />
                  </div>
                </div>

                <div className="space-y-3">
                  <h3 className="text-lg font-bold text-gray-900">
                    {schedule.title}
                  </h3>

                  <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-sm text-gray-600">
                    <span>
                      <span className="text-gray-400">채널:</span>{" "}
                      {schedule.channelName}
                    </span>
                    <span>
                      <span className="text-gray-400">업로드:</span>{" "}
                      {formatDatetime(schedule.date, schedule.time)}
                    </span>
                    <div className="flex items-center gap-2">
                      <span className="text-gray-400">유형:</span>
                      <button
                        type="button"
                        onClick={() => setVideoType("video")}
                        className="px-3 py-1 rounded-full text-xs font-medium bg-blue-500 text-white transition-colors"
                      >
                        Video
                      </button>
                      <button
                        type="button"
                        onClick={() => setVideoType("shorts")}
                        className="px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-500 hover:bg-gray-200 transition-colors"
                      >
                        Shorts
                      </button>
                    </div>
                  </div>

                  <a
                    href={videoUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="inline-flex items-center gap-2 text-sm text-red-500 hover:text-red-600 transition-colors"
                  >
                    <ExternalLink size={16} />
                    YouTube에서 보기
                  </a>
                </div>
              </motion.div>

              <motion.div
                variants={itemVariants}
                className="bg-white rounded-2xl shadow-sm p-8"
              >
                <div className="flex items-center justify-between mb-6">
                  <div className="flex items-center gap-2">
                    <Users size={20} className="text-primary" />
                    <h2 className="text-lg font-bold text-gray-900">출연 멤버</h2>
                  </div>
                  <button
                    type="button"
                    onClick={toggleAllMembers}
                    className="text-sm text-primary hover:underline"
                  >
                    {selectedMembers.length === members.length
                      ? "전체 해제"
                      : "전체 선택"}
                  </button>
                </div>

                <div className="grid grid-cols-5 gap-4">
                  {members.map((member) => {
                    const isSelected = selectedMembers.includes(member.id);
                    return (
                      <button
                        key={member.id}
                        type="button"
                        onClick={() => toggleMember(member.id)}
                        className={`relative rounded-xl overflow-hidden transition-all ${
                          isSelected
                            ? "ring-2 ring-primary ring-offset-2"
                            : "hover:opacity-80"
                        }`}
                      >
                        <div className="aspect-[3/4] bg-gray-100">
                          {member.image_url ? (
                            <img
                              src={member.image_url}
                              alt={member.name}
                              className="w-full h-full object-cover"
                            />
                          ) : (
                            <div className="w-full h-full flex items-center justify-center bg-gray-200">
                              <Users size={24} className="text-gray-400" />
                            </div>
                          )}
                        </div>
                        <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/70 to-transparent p-3">
                          <p className="text-white text-sm font-medium">
                            {member.name}
                          </p>
                        </div>
                        {isSelected && (
                          <div className="absolute top-2 right-2 w-6 h-6 bg-primary rounded-full flex items-center justify-center">
                            <Check size={14} className="text-white" />
                          </div>
                        )}
                      </button>
                    );
                  })}
                </div>
              </motion.div>
            </>
          )}

          {/* 버튼 */}
          <motion.div
            variants={itemVariants}
            className="flex items-center justify-end gap-4"
          >
            <button
              type="button"
              onClick={() => navigate("/admin/schedule")}
              className="px-6 py-3 text-gray-700 hover:bg-gray-100 rounded-xl transition-colors font-medium"
            >
              취소
            </button>
            <button
              type="submit"
              disabled={saving}
              className="flex items-center gap-2 px-6 py-3 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? (
                <>
                  <Loader2 size={18} className="animate-spin" />
                  저장 중...
                </>
              ) : (
                <>
                  <Save size={18} />
                  저장하기
                </>
              )}
            </button>
          </motion.div>
        </form>
      </motion.div>
    </AdminLayout>
  );
}

export default YouTubeEditForm;
