import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { motion } from "framer-motion";
import {
  Save, GraduationCap, MapPin, Link2, Image as ImageIcon, Users, X,
} 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 LocationSearchDialog from "@/components/pc/admin/schedule/LocationSearchDialog";
import { useToast } from "@/hooks/common";
import { useAdminAuth } from "@/hooks/pc/admin";
import { getMembers } from "@/api/public/members";
import { createEvent } from "@/api/admin/events";

// 세부 타입 목록 (현재는 "대학"만)
const SUBTYPES = [
  { value: "university", label: "대학 축제" },
];

function EventForm() {
  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 [subtype, setSubtype] = useState("university");
  const [title, setTitle] = useState("");
  const [schoolName, setSchoolName] = useState("");
  const [date, setDate] = useState("");
  const [time, setTime] = useState("");
  const [selectedMemberIds, setSelectedMemberIds] = useState([]);
  const [venue, setVenue] = useState(null);
  const [venueDialogOpen, setVenueDialogOpen] = useState(false);
  const [posterFiles, setPosterFiles] = useState([]); // [{file, preview}]
  const [postUrls, setPostUrls] = useState([]);
  const [urlInput, setUrlInput] = useState("");
  const [saving, setSaving] = useState(false);

  // 멤버 토글
  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 handlePosterChange = (e) => {
    const files = Array.from(e.target.files || []);
    const newItems = files.map((file) => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onloadend = () => resolve({ file, preview: reader.result });
        reader.readAsDataURL(file);
      });
    });
    Promise.all(newItems).then((items) => {
      setPosterFiles((prev) => [...prev, ...items]);
    });
    e.target.value = "";
  };
  const removePoster = (index) => {
    setPosterFiles((prev) => prev.filter((_, i) => i !== index));
  };

  // URL 추가/삭제
  const addUrl = () => {
    const url = urlInput.trim();
    if (!url) return;
    if (!postUrls.includes(url)) {
      setPostUrls([...postUrls, url]);
    }
    setUrlInput("");
  };
  const removeUrl = (index) => {
    setPostUrls(postUrls.filter((_, i) => i !== index));
  };

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

    if (!title.trim()) {
      setToast({ type: "error", message: "제목을 입력해주세요." });
      return;
    }
    if (!schoolName.trim()) {
      setToast({ type: "error", message: "학교명을 입력해주세요." });
      return;
    }
    if (!date) {
      setToast({ type: "error", message: "날짜를 선택해주세요." });
      return;
    }
    if (!venue) {
      setToast({ type: "error", message: "장소를 선택해주세요." });
      return;
    }

    setSaving(true);
    try {
      const payload = {
        subtype,
        title: title.trim(),
        schoolName: schoolName.trim(),
        date,
        time: time || null,
        memberIds: selectedMemberIds,
        venue,
        postUrls,
      };

      const formData = new FormData();
      formData.append("payload", JSON.stringify(payload));
      posterFiles.forEach((item) => {
        formData.append("posters", item.file);
      });

      await createEvent(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="block text-sm font-medium text-gray-700 mb-1.5">
                세부 타입
              </label>
              <div className="flex flex-wrap gap-2">
                {SUBTYPES.map((opt) => (
                  <button
                    key={opt.value}
                    type="button"
                    onClick={() => setSubtype(opt.value)}
                    className={`px-4 py-2 rounded-lg text-sm border transition-colors ${
                      subtype === opt.value
                        ? "border-primary bg-primary text-white"
                        : "border-gray-200 text-gray-600 hover:border-gray-300"
                    }`}
                  >
                    {opt.label}
                  </button>
                ))}
              </div>
            </div>

            {/* 제목 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1.5">
                제목 *
              </label>
              <input
                type="text"
                value={title}
                onChange={(e) => setTitle(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"
              />
            </div>

            {/* 학교명 */}
            <div>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-1.5">
                <GraduationCap size={14} />
                학교명 *
              </label>
              <input
                type="text"
                value={schoolName}
                onChange={(e) => setSchoolName(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"
              />
            </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>
              <label className="flex items-center gap-2 text-sm font-medium text-gray-700 mb-1.5">
                <MapPin size={14} />
                장소 *
              </label>
              {venue ? (
                <div className="flex items-start gap-3 p-3 border border-gray-200 rounded-lg">
                  <MapPin size={16} className="text-primary mt-0.5 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-gray-900">{venue.name}</p>
                    {venue.address && (
                      <p className="text-sm text-gray-500 truncate">{venue.address}</p>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => setVenueDialogOpen(true)}
                    className="text-sm text-primary hover:underline"
                  >
                    변경
                  </button>
                  <button
                    type="button"
                    onClick={() => setVenue(null)}
                    className="text-gray-400 hover:text-red-500"
                  >
                    <X size={16} />
                  </button>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => setVenueDialogOpen(true)}
                  className="w-full px-3 py-2.5 border border-dashed border-gray-300 rounded-lg text-sm text-gray-500 hover:border-primary hover:text-primary transition-colors"
                >
                  장소 검색
                </button>
              )}
            </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="flex items-center gap-2 text-lg font-bold text-gray-900 mb-4">
            <ImageIcon size={18} />
            포스터 <span className="text-sm font-normal text-gray-400">(선택, 여러 장 가능)</span>
          </h2>
          <div className="flex flex-wrap gap-3">
            {posterFiles.map((item, idx) => (
              <div key={idx} className="relative">
                <img src={item.preview} alt={`poster ${idx}`} className="h-32 w-32 object-cover rounded-lg border border-gray-200" />
                <button
                  type="button"
                  onClick={() => removePoster(idx)}
                  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 h-32 w-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">
                <ImageIcon size={20} className="mx-auto text-gray-400 mb-1" />
                <span className="text-xs text-gray-400">추가</span>
              </div>
              <input type="file" accept="image/*" multiple className="hidden" onChange={handlePosterChange} />
            </label>
          </div>
        </div>

        {/* URL */}
        <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-4">
            <Link2 size={18} />
            관련 URL <span className="text-sm font-normal text-gray-400">(선택, 여러 개 가능)</span>
          </h2>
          <div className="flex gap-2 mb-3">
            <input
              type="url"
              value={urlInput}
              onChange={(e) => setUrlInput(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter") {
                  e.preventDefault();
                  addUrl();
                }
              }}
              placeholder="https://www.instagram.com/p/... 또는 공식 페이지"
              className="flex-1 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"
            />
            <button
              type="button"
              onClick={addUrl}
              className="px-4 py-2.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
            >
              추가
            </button>
          </div>
          {postUrls.length > 0 && (
            <ul className="space-y-1.5">
              {postUrls.map((url, idx) => (
                <li key={idx} className="flex items-center justify-between gap-2 p-2 bg-gray-50 rounded-lg">
                  <a href={url} target="_blank" rel="noreferrer" className="flex-1 truncate text-sm text-gray-600 hover:underline">
                    {url}
                  </a>
                  <button
                    type="button"
                    onClick={() => removeUrl(idx)}
                    className="text-gray-400 hover:text-red-500"
                  >
                    <X size={16} />
                  </button>
                </li>
              ))}
            </ul>
          )}
        </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>

      {/* 장소 검색 다이얼로그 */}
      <LocationSearchDialog
        isOpen={venueDialogOpen}
        onClose={() => setVenueDialogOpen(false)}
        onSelect={(place) => setVenue(place)}
      />
    </>
  );
}

export default EventForm;
