import React, { useCallback, useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18n-lite";
import { booksApi } from "../api/books";
import type { BookDetail } from "../types/book";
import { useMediaQuery, BREAKPOINTS } from "../hooks/useMediaQuery";

export function BookDetailPage() {
  const { t } = useTranslation();
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [book, setBook] = useState<BookDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const isMobile = useMediaQuery(BREAKPOINTS.md);

  const loadBook = useCallback(async () => {
    if (!id) return;
    setLoading(true);
    setError(null);
    try {
      const bookId = Number(id);
      if (Number.isNaN(bookId)) {
        setError(t("bookDetail.invalidId"));
        return;
      }
      const data = await booksApi.getBook(bookId);
      setBook(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : t("bookDetail.loadFailed"));
    } finally {
      setLoading(false);
    }
  }, [id, t]);

  useEffect(() => {
    void loadBook();
  }, [loadBook]);

  const statusColors: Record<string, { bg: string; text: string }> = {
    want_to_read: { bg: "#dbeafe", text: "#1d4ed8" },
    reading: { bg: "#dcfce7", text: "#16a34a" },
    finished: { bg: "#f3e8ff", text: "#9333ea" },
    dnf: { bg: "#fef3c7", text: "#b45309" },
  };

  const containerStyle: React.CSSProperties = {
    maxWidth: 720,
    margin: "0 auto",
    padding: isMobile ? 16 : 24,
    minHeight: "100vh",
    background: "#f8f9fa",
  };

  const backButtonStyle: React.CSSProperties = {
    display: "inline-flex",
    alignItems: "center",
    gap: 4,
    padding: isMobile ? "10px 16px" : "8px 16px",
    borderRadius: 8,
    border: "1px solid #e5e7eb",
    background: "#fff",
    color: "#374151",
    fontSize: isMobile ? 15 : 14,
    cursor: "pointer",
    marginBottom: isMobile ? 16 : 24,
    minHeight: 44,
  };

  if (loading) {
    return (
      <div style={containerStyle}>
        <div style={{ height: 32, width: 80, background: "#e5e7eb", borderRadius: 6, marginBottom: 24 }} />
        <div style={{ display: "flex", gap: isMobile ? 16 : 24, flexDirection: isMobile ? "column" : "row" }}>
          <div style={{
            width: isMobile ? 140 : 240,
            height: isMobile ? 210 : 360,
            background: "#e5e7eb",
            borderRadius: 12,
            flexShrink: 0,
            alignSelf: isMobile ? "center" : "flex-start",
          }} />
          <div style={{ flex: 1 }}>
            <div style={{ height: 28, background: "#e5e7eb", borderRadius: 6, marginBottom: 12, width: "60%" }} />
            <div style={{ height: 18, background: "#e5e7eb", borderRadius: 4, marginBottom: 8, width: "40%" }} />
            <div style={{ height: 18, background: "#e5e7eb", borderRadius: 4, marginBottom: 8, width: "30%" }} />
            <div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, marginBottom: 4, width: "90%" }} />
            <div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, marginBottom: 4, width: "80%" }} />
            <div style={{ height: 14, background: "#e5e7eb", borderRadius: 4, width: "70%" }} />
          </div>
        </div>
      </div>
    );
  }

  if (error || !book) {
    return (
      <div style={containerStyle}>
        <button onClick={() => navigate("/")} style={backButtonStyle}>← {t("bookDetail.backToLibrary")}</button>
        <div style={{ textAlign: "center", padding: isMobile ? "60px 16px" : "80px 20px" }}>
          <div style={{ fontSize: isMobile ? 48 : 64, marginBottom: 16 }}>😕</div>
          <h2 style={{ fontSize: isMobile ? 18 : 20, color: "#1f2937", marginBottom: 8 }}>{t("bookDetail.notFound")}</h2>
          <p style={{ color: "#6b7280", marginBottom: 20 }}>{error || t("bookDetail.notFoundDescription")}</p>
          <button onClick={() => void loadBook()} className="btn" style={{ padding: "12px 24px", fontSize: 15, minHeight: 44 }}>{t("common.retry")}</button>
        </div>
      </div>
    );
  }

  const sc = statusColors[book.reading_status] ?? { bg: "#f3f4f6", text: "#6b7280" };
  const dateFormat: Intl.DateTimeFormatOptions = { year: "numeric", month: "long", day: "numeric" };

  return (
    <div style={containerStyle}>
      <button onClick={() => navigate("/")} style={backButtonStyle}>
        ← {isMobile ? t("bookDetail.back") : t("bookDetail.backToLibrary")}
      </button>

      <div style={{ display: "flex", gap: isMobile ? 20 : 32, flexDirection: isMobile ? "column" : "row" }}>
        <div style={{ flexShrink: 0, alignSelf: isMobile ? "center" : "flex-start" }}>
          <div style={{
            width: isMobile ? 160 : 240,
            height: isMobile ? 240 : 360,
            borderRadius: 12,
            overflow: "hidden",
            background: "#f0f0f0",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            boxShadow: "0 4px 20px rgba(0,0,0,0.1)",
          }}>
            {book.cover_image
              ? <img src={book.cover_image} alt={book.title} style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              : <span style={{ fontSize: isMobile ? 48 : 80 }}>📖</span>}
          </div>
        </div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <h1 style={{ fontSize: isMobile ? 22 : 28, fontWeight: 700, color: "#1f2937", marginBottom: 8, lineHeight: 1.2 }}>
            {book.title}
          </h1>

          {book.author && (
            <p style={{ fontSize: isMobile ? 16 : 18, color: "#4b5563", marginBottom: 6 }}>
              {t("bookDetail.byAuthor", { author: book.author })}
            </p>
          )}

          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16, marginTop: 12 }}>
            <span style={{ background: sc.bg, color: sc.text, fontSize: 13, fontWeight: 600, padding: "4px 12px", borderRadius: 999, minHeight: 28, display: "inline-flex", alignItems: "center" }}>
              {book.reading_status_display}
            </span>
            {book.genre && (
              <span style={{ background: "#eef2ff", color: "#4f46e5", fontSize: 13, padding: "4px 12px", borderRadius: 999, minHeight: 28, display: "inline-flex", alignItems: "center" }}>
                {book.genre}
              </span>
            )}
            {book.total_pages > 0 && (
              <span style={{ background: "#f3f4f6", color: "#6b7280", fontSize: 13, padding: "4px 12px", borderRadius: 999, minHeight: 28, display: "inline-flex", alignItems: "center" }}>
                {t("bookDetail.pages", { count: String(book.total_pages) })}
              </span>
            )}
          </div>

          {book.description && (
            <div style={{ marginTop: 20 }}>
              <h3 style={{ fontSize: 16, fontWeight: 600, color: "#1f2937", marginBottom: 8 }}>{t("bookDetail.description")}</h3>
              <p style={{ fontSize: isMobile ? 15 : 15, color: "#4b5563", lineHeight: 1.7, whiteSpace: "pre-wrap" }}>
                {book.description}
              </p>
            </div>
          )}

          <div style={{ marginTop: 24, paddingTop: 16, borderTop: "1px solid #e5e7eb" }}>
            <p style={{ fontSize: 13, color: "#9ca3af" }}>
              {t("bookDetail.added", { date: new Date(book.created_at).toLocaleDateString(undefined, dateFormat) })}
              {book.created_at !== book.updated_at && ` · ${t("bookDetail.updated", { date: new Date(book.updated_at).toLocaleDateString(undefined, dateFormat) })}`}
            </p>
          </div>

          {isMobile && (
            <div style={{ marginTop: 24 }}>
              <button
                onClick={() => navigate("/")}
                style={{
                  width: "100%",
                  padding: "14px 24px",
                  borderRadius: 10,
                  border: "none",
                  background: "#4f46e5",
                  color: "#fff",
                  fontSize: 15,
                  fontWeight: 600,
                  cursor: "pointer",
                  minHeight: 44,
                }}
              >
                ← {t("bookDetail.backToLibrary")}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
