import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Save, Tv, Link2, Image, Users } from "lucide-react";

import Toast from "@/components/common/Toast";
import DatePicker from "@/components/pc/admin/common/DatePicker";
import TimePicker from "@/components/pc/admin/common/TimePicker";
import { useToast } from "@/hooks/common";
import { useAdminAuth } from "@/hooks/pc/admin";
import { getMembers } from "@/api/public/members";
import { createVarietySchedule, getBroadcasters } from "@/api/admin/variety";

/**
 * 예능 일정 추가 폼
 */
function VarietyForm() {
  const navigate = useNavigate();
  const { toast, setToast } = useToast();
  const { isAuthenticated } = useAdminAuth();

  // 멤버 목록
  const { data: membersData = [] } = useQuery({
    queryKey: ["members"],
    queryFn: getMembers,
    enabled: isAuthenticated,
    staleTime: 5 * 60 * 1000,
  });
  const members = membersData.filter((m) => !m.is_former);

  // 폼 상태
  const [title, setTitle] = useState("");
  const [broadcaster, setBroadcaster] = useState("");
  const [date, setDate] = useState("");
  const [time, setTime] = useState("");
  const [replayUrl, setReplayUrl] = useState("");
  const [thumbnailFile, setThumbnailFile] = useState(null);
  const [thumbnailPreview, setThumbnailPreview] = useState(null);
  const [selectedMemberIds, setSelectedMemberIds] = useState([]);
  const [saving, setSaving] = useState(false);

  // 자주 사용된 방송사 목록
  const { data: broadcasterPresets = [] } = useQuery({
    queryKey: ["broadcasters"],
    queryFn: getBroadcasters,
    enabled: isAuthenticated,
    staleTime: 5 * 60 * 1000,
  });

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

  const toggleAllMembers = () => {
    if (selectedMemberIds.length === members.length) {
      setSelectedMemberIds([]);
    } else {
      setSelectedMemberIds(members.map((m) => m.id));
    }
  };

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

    if (!title.trim()) {
      setToast({ type: "error", message: "프로그램명을 입력해주세요." });
      return;
    }
    if (!broadcaster.trim()) {
      setToast({ type: "error", message: "방송사/플랫폼을 선택하거나 입력해주세요." });
      return;
    }
    if (!date) {
      setToast({ type: "error", message: "날짜를 선택해주세요." });
      return;
    }

    setSaving(true);

    try {
      const formData = new FormData();
      formData.append("title", title.trim());
      formData.append("broadcaster", broadcaster.trim());
      formData.append("date", date);
      if (time) formData.append("time", time);
      if (replayUrl.trim()) formData.append("replayUrl", replayUrl.trim());
      formData.append("memberIds", JSON.stringify(selectedMemberIds));
      if (thumbnailFile) formData.append("thumbnail", thumbnailFile);

      await createVarietySchedule(formData);

      sessionStorage.setItem(
        "scheduleToast",
        JSON.stringify({ type: "success", message: "예능 일정이 추가되었습니다." })
      );
      navigate("/admin/schedule");
    } catch (err) {
      console.error("예능 일정 저장 실패:", err);
      setToast({ type: "error", message: err.message || "저장에 실패했습니다." });
    } finally {
      setSaving(false);
    }
  };

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

      <motion.form
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4, ease: [0.25, 0.1, 0.25, 1] }}
        onSubmit={handleSubmit}
        className="space-y-6"
      >
        {/* 프로그램 정보 */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <h2 className="text-lg font-bold text-gray-900 mb-6">프로그램 정보</h2>

          <div className="space-y-4">
            {/* 프로그램명 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-1.5">
                <Tv size={14} />
                프로그램명 *
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                placeholder="예: 워크돌 EP.15"
                className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
            </div>

            {/* 방송사/플랫폼 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-1.5">
                방송사/플랫폼 *
              </label>
              <input
                type="text"
                value={broadcaster}
                onChange={(e) => setBroadcaster(e.target.value)}
                placeholder="방송사 또는 플랫폼명"
                className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent mb-2"
              />
              <div className="flex flex-wrap gap-1.5">
                {broadcasterPresets.map((preset) => (
                  <button
                    key={preset}
                    type="button"
                    onClick={() => setBroadcaster(preset)}
                    className={`px-3 py-1 text-xs rounded-full border transition-colors ${
                      broadcaster === preset
                        ? "border-primary bg-primary text-white"
                        : "border-gray-200 text-gray-500 hover:border-gray-300"
                    }`}
                  >
                    {preset}
                  </button>
                ))}
              </div>
            </div>

            {/* 날짜/시간 */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1.5 block">날짜 *</label>
                <DatePicker value={date} onChange={setDate} />
              </div>
              <div>
                <label className="text-sm font-medium text-gray-700 mb-1.5 block">시간 (선택)</label>
                <TimePicker value={time} onChange={setTime} />
              </div>
            </div>
          </div>
        </div>

        {/* 출연 멤버 */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <h2 className="flex items-center gap-2 text-lg font-bold text-gray-900 mb-6">
            <Users size={18} />
            출연 멤버
          </h2>

          <div className="flex flex-wrap gap-2">
            <button
              type="button"
              onClick={toggleAllMembers}
              className={`flex items-center justify-center px-4 py-1.5 rounded-full border text-sm transition-colors ${
                selectedMemberIds.length === members.length
                  ? "border-primary bg-primary text-white"
                  : "border-gray-200 text-gray-500 hover:border-gray-300"
              }`}
            >
              {selectedMemberIds.length === members.length ? "전체 해제" : "전체 선택"}
            </button>
            {members.map((member) => {
              const isSelected = selectedMemberIds.includes(member.id);
              return (
                <button
                  key={member.id}
                  type="button"
                  onClick={() => toggleMember(member.id)}
                  className={`flex items-center gap-2 pr-3.5 pl-1.5 py-1.5 rounded-full border transition-colors ${
                    isSelected ? "border-primary" : "border-gray-200"
                  }`}
                >
                  <div className="w-9 h-9 rounded-full overflow-hidden bg-gray-200 flex-shrink-0">
                    {member.image_url ? (
                      <img src={member.image_url} alt={member.name} className="w-full h-full object-cover" />
                    ) : (
                      <div className="w-full h-full bg-gray-300" />
                    )}
                  </div>
                  <span className="text-sm text-gray-700">{member.name}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* 추가 정보 */}
        <div className="bg-white rounded-2xl border border-gray-100 shadow-sm p-6">
          <h2 className="text-lg font-bold text-gray-900 mb-6">추가 정보</h2>

          <div className="space-y-4">
            {/* 다시보기 링크 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-1.5">
                <Link2 size={14} />
                다시보기 링크 (선택)
              </label>
              <input
                type="url"
                value={replayUrl}
                onChange={(e) => setReplayUrl(e.target.value)}
                placeholder="https://www.youtube.com/watch?v=... 또는 OTT 링크"
                className="w-full px-3 py-2.5 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
            </div>

            {/* 썸네일 이미지 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-1.5">
                <Image size={14} />
                썸네일 이미지 (선택)
              </label>
              {thumbnailPreview ? (
                <div className="relative inline-block">
                  <img src={thumbnailPreview} alt="썸네일 미리보기" className="h-32 rounded-lg object-cover" />
                  <button
                    type="button"
                    onClick={() => { setThumbnailFile(null); setThumbnailPreview(null); }}
                    className="absolute -top-2 -right-2 w-6 h-6 bg-red-500 text-white rounded-full text-xs flex items-center justify-center hover:bg-red-600"
                  >
                    ✕
                  </button>
                </div>
              ) : (
                <label className="flex items-center justify-center w-full h-32 border-2 border-dashed border-gray-200 rounded-lg cursor-pointer hover:border-primary/50 hover:bg-primary/5 transition-colors">
                  <div className="text-center">
                    <Image size={24} className="mx-auto text-gray-400 mb-1" />
                    <span className="text-sm text-gray-400">클릭하여 이미지 선택</span>
                  </div>
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={(e) => {
                      const file = e.target.files[0];
                      if (file) {
                        setThumbnailFile(file);
                        const reader = new FileReader();
                        reader.onloadend = () => setThumbnailPreview(reader.result);
                        reader.readAsDataURL(file);
                      }
                    }}
                  />
                </label>
              )}
            </div>
          </div>
        </div>

        {/* 버튼 */}
        <div className="flex items-center justify-end gap-4">
          <button
            type="button"
            onClick={() => navigate("/admin/schedule")}
            className="px-6 py-2.5 text-gray-600 hover:text-gray-900 transition-colors"
          >
            취소
          </button>
          <button
            type="submit"
            disabled={saving}
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors disabled:opacity-50"
          >
            {saving ? (
              <>
                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                저장 중...
              </>
            ) : (
              <>
                <Save size={18} />
                저장
              </>
            )}
          </button>
        </div>
      </motion.form>
    </>
  );
}

export default VarietyForm;
