import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import {
  Hash,
  Loader2,
  Check,
  AlertCircle,
  Save,
  Image as ImageIcon,
} from "lucide-react";

import Toast from "@/components/common/Toast";
import { useToast } from "@/hooks/common";
import useAuthStore from "@/stores/useAuthStore";

// X 로고 아이콘
const XLogo = ({ size = 24, className = "" }) => (
  <svg
    width={size}
    height={size}
    viewBox="0 0 24 24"
    fill="currentColor"
    className={className}
  >
    <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
  </svg>
);

/**
 * X(Twitter) 일정 추가 폼
 * - 게시글 ID 입력 시 자동으로 정보 조회
 */
function XForm() {
  const navigate = useNavigate();
  const { toast, setToast } = useToast();

  const [postId, setPostId] = useState("");
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [postInfo, setPostInfo] = useState(null);
  const [error, setError] = useState(null);

  // 게시글 ID 추출 (URL에서도 추출 가능)
  const extractPostId = (input) => {
    // 숫자만 있으면 그대로 반환
    if (/^\d+$/.test(input.trim())) {
      return input.trim();
    }
    // URL에서 추출
    const match = input.match(/status\/(\d+)/);
    return match ? match[1] : null;
  };

  // X 게시글 정보 조회
  const fetchPostInfo = async () => {
    const id = extractPostId(postId);
    if (!id) {
      setError("게시글 ID 또는 URL을 입력해주세요.");
      return;
    }

    setLoading(true);
    setError(null);
    setPostInfo(null);

    try {
      const token = useAuthStore.getState().token;
      const response = await fetch(
        `/api/admin/x/post-info?postId=${id}`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

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

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

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

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

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

    if (!postInfo) {
      setError("먼저 게시글 ID를 입력하고 조회해주세요.");
      return;
    }

    setSaving(true);

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

      const response = await fetch("/api/admin/x/schedule", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${token}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          postId: postInfo.postId,
          title: postInfo.title,
          content: postInfo.text,
          imageUrls: postInfo.imageUrls,
          date: postInfo.date,
          time: postInfo.time,
        }),
      });

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

      sessionStorage.setItem(
        "scheduleToast",
        JSON.stringify({
          type: "success",
          message: "X 일정이 추가되었습니다.",
        })
      );
      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">
        {/* 게시글 ID 입력 */}
        <div className="bg-white rounded-2xl shadow-sm p-8">
          <div className="flex items-center gap-2 mb-6">
            <XLogo size={24} className="text-black" />
            <h2 className="text-lg font-bold text-gray-900">X 게시글</h2>
          </div>

          <div className="space-y-4">
            {/* ID 입력 필드 */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                게시글 ID 또는 URL *
              </label>
              <div className="flex gap-2">
                <div className="flex-1 relative">
                  <Hash
                    size={18}
                    className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400"
                  />
                  <input
                    type="text"
                    value={postId}
                    onChange={(e) => setPostId(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="1234567890 또는 https://x.com/realfromis_9/status/1234567890"
                    className="w-full pl-12 pr-4 py-3 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-gray-900 focus:border-transparent"
                    disabled={loading || postInfo}
                  />
                </div>
                {!postInfo ? (
                  <button
                    type="button"
                    onClick={fetchPostInfo}
                    disabled={loading || !postId.trim()}
                    className="px-6 py-3 bg-black text-white rounded-xl hover:bg-gray-800 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>
            )}

            {/* 게시글 정보 미리보기 */}
            {postInfo && (
              <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-center gap-2 mb-4">
                  <Check size={18} className="text-green-500" />
                  <span className="text-sm font-medium text-green-600">
                    게시글 정보를 가져왔습니다
                  </span>
                </div>

                {/* 프로필 */}
                {postInfo.profile?.displayName && (
                  <div className="flex items-center gap-3 mb-4 pb-4 border-b border-green-200">
                    {postInfo.profile.avatarUrl && (
                      <img
                        src={postInfo.profile.avatarUrl}
                        alt=""
                        className="w-10 h-10 rounded-full"
                      />
                    )}
                    <div>
                      <p className="font-bold text-gray-900">
                        {postInfo.profile.displayName}
                      </p>
                      <p className="text-sm text-gray-500">@{postInfo.username}</p>
                    </div>
                  </div>
                )}

                {/* 제목 (첫 문단) */}
                <div className="mb-4">
                  <p className="text-xs text-gray-400 mb-1">제목 (자동 추출)</p>
                  <p className="text-lg font-bold text-gray-900">{postInfo.title}</p>
                </div>

                {/* 전체 내용 */}
                <div className="mb-4">
                  <p className="text-xs text-gray-400 mb-1">전체 내용</p>
                  <p className="text-gray-700 whitespace-pre-wrap text-sm">
                    {postInfo.text}
                  </p>
                </div>

                {/* 이미지 */}
                {postInfo.imageUrls?.length > 0 && (
                  <div className="mb-4">
                    <p className="text-xs text-gray-400 mb-2 flex items-center gap-1">
                      <ImageIcon size={12} />
                      이미지 ({postInfo.imageUrls.length}개)
                    </p>
                    <div className="grid grid-cols-4 gap-2">
                      {postInfo.imageUrls.map((url, index) => (
                        <div
                          key={index}
                          className="aspect-square bg-gray-200 rounded-lg overflow-hidden"
                        >
                          <img
                            src={url}
                            alt={`이미지 ${index + 1}`}
                            className="w-full h-full object-cover"
                          />
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* 날짜/시간 */}
                <div className="text-sm text-gray-500">
                  <span className="text-gray-400">게시:</span>{" "}
                  {postInfo.date} {postInfo.time}
                </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={!postInfo || 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 XForm;
