import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion";
import { Save, Loader2, Tv, Link2, Image, Users } from "lucide-react";
import DatePicker from "@/components/pc/admin/common/DatePicker";
import TimePicker from "@/components/pc/admin/common/TimePicker";

import AdminLayout from "@/components/pc/admin/layout/Layout";
import Toast from "@/components/common/Toast";
import { useToast } from "@/hooks/common";
import { useAdminAuth } from "@/hooks/pc/admin";
import { getMembers } from "@/api/public/members";
import { getVarietySchedule, updateVarietySchedule, getBroadcasters } from "@/api/admin/variety";


/**
 * 예능 일정 수정 폼
 */
function VarietyEditForm() {
  const { id } = useParams();
  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 { data: scheduleData, isLoading } = useQuery({
    queryKey: ["variety-schedule", id],
    queryFn: () => getVarietySchedule(id),
    enabled: isAuthenticated && !!id,
  });

  const { data: broadcasterPresets = [] } = useQuery({
    queryKey: ["broadcasters"],
    queryFn: getBroadcasters,
    enabled: isAuthenticated,
    staleTime: 5 * 60 * 1000,
  });

  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 [removeThumbnail, setRemoveThumbnail] = useState(false);
  const [selectedMemberIds, setSelectedMemberIds] = useState([]);
  const [saving, setSaving] = useState(false);
  const [initialized, setInitialized] = useState(false);

  useEffect(() => {
    if (scheduleData && !initialized) {
      setTitle(scheduleData.title || "");
      setBroadcaster(scheduleData.broadcaster || "");
      setDate(scheduleData.date || "");
      setTime(scheduleData.time || "");
      setReplayUrl(scheduleData.replayUrl || "");
      if (scheduleData.thumbnailUrl) setThumbnailPreview(scheduleData.thumbnailUrl);
      setSelectedMemberIds(scheduleData.memberIds || []);
      setInitialized(true);
    }
  }, [scheduleData, initialized]);

  const toggleMember = (memberId) => {
    setSelectedMemberIds((prev) =>
      prev.includes(memberId) ? prev.filter((i) => i !== memberId) : [...prev, memberId]
    );
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!title.trim() || !broadcaster.trim() || !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);
      if (removeThumbnail) formData.append("removeThumbnail", "true");

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

  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 text-primary animate-spin" />
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <Toast toast={toast} onClose={() => setToast(null)} />
      <motion.form
        initial={{ opacity: 0, y: 12 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
        onSubmit={handleSubmit}
        className="space-y-6 max-w-4xl mx-auto px-6 py-8"
      >
        {/* 프로그램 정보 */}
        <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="text-sm font-medium text-gray-700 mb-1.5 block">방송사/플랫폼 *</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((p) => (
                  <button key={p} type="button" onClick={() => setBroadcaster(p)} className={`px-3 py-1 text-xs rounded-full border transition-colors ${broadcaster === p ? "border-primary bg-primary text-white" : "border-gray-200 text-gray-500 hover:border-gray-300"}`}>{p}</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={`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((m) => (
              <button key={m.id} type="button" onClick={() => toggleMember(m.id)} className={`flex items-center gap-2 pr-3.5 pl-1.5 py-1.5 rounded-full border transition-colors ${selectedMemberIds.includes(m.id) ? "border-primary" : "border-gray-200"}`}>
                <div className="w-9 h-9 rounded-full overflow-hidden bg-gray-200 flex-shrink-0">{m.image_url ? <img src={m.image_url} alt={m.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">{m.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://..." 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); setRemoveThumbnail(true); }} 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 f = e.target.files[0]; if (f) { setThumbnailFile(f); setRemoveThumbnail(false); const r = new FileReader(); r.onloadend = () => setThumbnailPreview(r.result); r.readAsDataURL(f); } }} />
                </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>
    </AdminLayout>
  );
}

export default VarietyEditForm;
