import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import {
  Youtube,
  Link as LinkIcon,
  Loader2,
  Check,
  AlertCircle,
  Save,
} from "lucide-react";
import Toast from "@/components/common/Toast";
import { useToast } from "@/hooks/common";
import useAuthStore from "@/stores/useAuthStore";

/**
 * YouTube 일정 추가 폼
 * - URL 입력 시 자동으로 영상 정보 조회
 * - 조회된 정보로 일정 저장
 */
function YouTubeForm() {
  const navigate = useNavigate();
  const { toast, setToast } = useToast();

  const [url, setUrl] = useState("");
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [videoInfo, setVideoInfo] = useState(null);
  const [error, setError] = useState(null);

  // YouTube URL에서 영상 정보 조회
  const fetchVideoInfo = async () => {
    if (!url.trim()) {
      setError("YouTube URL을 입력해주세요.");
      return;
    }

    setLoading(true);
    setError(null);
    setVideoInfo(null);

    try {
      const token = useAuthStore.getState().token;
      const response = await fetch(
        `/api/admin/youtube/video-info?url=${encodeURIComponent(url)}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "영상 정보를 가져올 수 없습니다.");
      }

      const data = await response.json();
      setVideoInfo(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  // URL 입력 후 엔터 키
  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      e.preventDefault();
      fetchVideoInfo();
    }
  };

  // 초기화
  const handleReset = () => {
    setUrl("");
    setVideoInfo(null);
    setError(null);
  };

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

    if (!videoInfo) {
      setError("먼저 YouTube URL을 입력하고 조회해주세요.");
      return;
    }

    setSaving(true);

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

      const response = await fetch("/api/admin/youtube/schedule", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          videoId: videoInfo.videoId,
          title: videoInfo.title,
          channelId: videoInfo.channelId,
          channelName: videoInfo.channelName,
          date: videoInfo.date,
          time: videoInfo.time,
          videoType: videoInfo.videoType,
        }),
      });

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

      // 성공 메시지를 sessionStorage에 저장하고 목록 페이지로 이동
      sessionStorage.setItem(
        "scheduleToast",
        JSON.stringify({
          type: "success",
          message: "YouTube 일정이 추가되었습니다.",
        })
      );
      navigate("/admin/schedule");
    } catch (err) {
      setToast({
        type: "error",
        message: err.message,
      });
    } finally {
      setSaving(false);
    }
  };

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

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* YouTube URL 입력 */}
        <div 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">YouTube 영상</h2>
          </div>

          <div className="space-y-4">
            {/* URL 입력 필드 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                YouTube URL *
              </label>
              <div className="flex gap-2">
                <div className="flex-1 relative">
                  <LinkIcon
                    size={18}
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
                  />
                  <input
                    type="url"
                    value={url}
                    onChange={(e) => setUrl(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="https://www.youtube.com/watch?v=... 또는 https://youtu.be/..."
                    className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-red-500 focus:border-transparent"
                    disabled={loading || videoInfo}
                  />
                </div>
                {!videoInfo ? (
                  <button
                    type="button"
                    onClick={fetchVideoInfo}
                    disabled={loading || !url.trim()}
                    className="px-6 py-3 bg-red-500 text-white rounded-xl hover:bg-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 whitespace-nowrap"
                  >
                    {loading ? (
                      <>
                        <Loader2 size={18} className="animate-spin" />
                        조회 중...
                      </>
                    ) : (
                      "조회"
                    )}
                  </button>
                ) : (
                  <button
                    type="button"
                    onClick={handleReset}
                    className="px-6 py-3 bg-gray-100 text-gray-600 rounded-xl hover:bg-gray-200 transition-colors whitespace-nowrap"
                  >
                    다시 입력
                  </button>
                )}
              </div>
            </div>

            {/* 에러 메시지 */}
            {error && (
              <motion.div
                initial={{ opacity: 0, y: -10 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex items-center gap-2 p-4 bg-red-50 text-red-600 rounded-xl"
              >
                <AlertCircle size={18} />
                <span>{error}</span>
              </motion.div>
            )}

            {/* 영상 정보 미리보기 */}
            {videoInfo && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="border border-green-200 bg-green-50 rounded-xl p-6"
              >
                <div className="flex items-start gap-4">
                  {/* 썸네일 */}
                  <div className="flex-shrink-0 w-48 aspect-video bg-gray-200 rounded-lg overflow-hidden">
                    <img
                      src={`https://img.youtube.com/vi/${videoInfo.videoId}/mqdefault.jpg`}
                      alt={videoInfo.title}
                      className="w-full h-full object-cover"
                    />
                  </div>

                  {/* 정보 */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-2">
                      <Check size={18} className="text-green-500" />
                      <span className="text-sm font-medium text-green-600">
                        영상 정보를 가져왔습니다
                      </span>
                    </div>

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

                    <div className="space-y-1 text-sm text-gray-600">
                      <p>
                        <span className="text-gray-400">채널:</span>{" "}
                        {videoInfo.channelName}
                      </p>
                      <p>
                        <span className="text-gray-400">업로드:</span>{" "}
                        {videoInfo.date} {videoInfo.time}
                      </p>
                      <p>
                        <span className="text-gray-400">유형:</span>{" "}
                        <span
                          className={`px-2 py-0.5 rounded-full text-xs font-medium ${
                            videoInfo.videoType === "shorts"
                              ? "bg-pink-100 text-pink-600"
                              : "bg-blue-100 text-blue-600"
                          }`}
                        >
                          {videoInfo.videoType === "shorts" ? "Shorts" : "Video"}
                        </span>
                      </p>
                    </div>
                  </div>
                </div>
              </motion.div>
            )}
          </div>
        </div>

        {/* 버튼 */}
        <div 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={!videoInfo || 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>
        </div>
      </form>
    </>
  );
}

export default YouTubeForm;
