import { useEffect, useState } from "react";
import { apiGet } from "../../api";
import { PageHead, StatCard, Empty, Loading, fmtNumber } from "../../components/ui";
import { IconBook, IconClock, IconHeadphones, IconRefresh, IconUser } from "../../components/icons";
import { useToast } from "../../lib/toast";

interface LibraryView {
  id: string;
  name: string;
  media_type: string;
  items: number;
  authors: number;
  duration: number;
  size: number;
}
interface Stats {
  library_count: number;
  book_count: number;
  podcast_count: number;
  author_count: number;
  total_duration: number;
  total_size: number;
  num_audio_tracks: number;
  libraries: LibraryView[];
}

function fmtHours(seconds: number): string {
  if (!seconds) return "0h";
  const h = Math.floor(seconds / 3600);
  if (h >= 24) return `${(h / 24).toFixed(0)}d ${h % 24}h`;
  const m = Math.floor((seconds % 3600) / 60);
  return h > 0 ? `${h}h ${m}m` : `${m}m`;
}
function fmtSize(bytes: number): string {
  if (!bytes) return "0 B";
  const units = ["B", "KB", "MB", "GB", "TB"];
  let v = bytes;
  let i = 0;
  while (v >= 1024 && i < units.length - 1) {
    v /= 1024;
    i++;
  }
  return `${v.toFixed(1)} ${units[i]}`;
}

export default function AudiobookshelfOverview() {
  const toast = useToast();
  const [status, setStatus] = useState<{ connected: boolean; configured: boolean; error?: string } | null>(null);
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);

  function load() {
    setLoading(true);
    apiGet("/api/audiobookshelf/status")
      .then((s) => {
        setStatus(s);
        if (s.connected) {
          return apiGet<Stats>("/api/audiobookshelf/stats").then(setStats);
        }
        setStats(null);
      })
      .catch(() => setStatus({ connected: false, configured: false }))
      .finally(() => setLoading(false));
  }
  useEffect(load, []);

  return (
    <>
      <div className="row between" style={{ alignItems: "flex-start" }}>
        <PageHead title="Audiobookshelf" icon={<IconBook />} />
        <button className="btn btn-sm" onClick={load} disabled={loading}>
          {loading ? <span className="spinner" /> : <IconRefresh />} Refresh
        </button>
      </div>

      {loading ? (
        <Loading label="Loading Audiobookshelf stats…" />
      ) : !status?.configured ? (
        <div className="panel">
          <Empty icon={<IconBook />}>
            Audiobookshelf is not configured. Add your server URL and API token in <strong>Settings</strong>.
          </Empty>
        </div>
      ) : !status.connected ? (
        <div className="panel">
          <Empty icon={<IconBook />}>Could not connect to Audiobookshelf. {status.error}</Empty>
        </div>
      ) : (
        <>
          <div className="stat-row" style={{ marginBottom: 14 }}>
            <StatCard icon={<IconBook />} value={fmtNumber(stats?.book_count)} label="Audiobooks" />
            <StatCard icon={<IconHeadphones />} value={fmtNumber(stats?.podcast_count)} label="Podcasts" />
            <StatCard icon={<IconUser />} value={fmtNumber(stats?.author_count)} label="Authors" />
            <StatCard icon={<IconClock />} value={fmtHours(stats?.total_duration || 0)} label="Total runtime" />
          </div>
          <div className="stat-row" style={{ marginBottom: 26 }}>
            <StatCard icon={<IconBook />} value={fmtNumber(stats?.library_count)} label="Libraries" />
            <StatCard icon={<IconHeadphones />} value={fmtNumber(stats?.num_audio_tracks)} label="Audio tracks" />
            <StatCard icon={<IconBook />} value={fmtSize(stats?.total_size || 0)} label="On disk" />
          </div>

          <div className="panel">
            <div className="panel-head">
              <h3 className="grow">Libraries</h3>
              <span className="sub">{stats?.libraries.length || 0}</span>
            </div>
            {!stats?.libraries.length ? (
              <Empty icon={<IconBook />}>No libraries found.</Empty>
            ) : (
              <table className="data-table">
                <thead>
                  <tr>
                    <th>Library</th>
                    <th>Type</th>
                    <th>Items</th>
                    <th>Authors</th>
                    <th>Runtime</th>
                    <th>Size</th>
                  </tr>
                </thead>
                <tbody>
                  {stats.libraries.map((lib) => (
                    <tr key={lib.id}>
                      <td className="cell-strong">{lib.name}</td>
                      <td>
                        <span className={`badge ${lib.media_type === "podcast" ? "badge-warn" : "badge-accent"}`}>
                          {lib.media_type}
                        </span>
                      </td>
                      <td className="mono">{fmtNumber(lib.items)}</td>
                      <td className="mono">{fmtNumber(lib.authors)}</td>
                      <td className="mono cell-sub">{fmtHours(lib.duration)}</td>
                      <td className="mono cell-sub">{fmtSize(lib.size)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            )}
          </div>
        </>
      )}
    </>
  );
}
