import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, formatUsd } from "../services/api";
import { StatusBadge } from "../components/StatusBadge";
import { motion } from "motion/react";
import { useAuth } from "../hooks/useAuth";
import { usePageTitle } from "../hooks/usePageTitle";
import {
  Settings2,
  RefreshCw,
  ArrowRight,
  ExternalLink,
  Rocket,
  Users,
  FolderGit2,
  Server,
  Activity,
  DollarSign,
  type LucideIcon,
} from "lucide-react";

interface RecentPreview {
  id: number;
  prNumber: number;
  prTitle: string;
  status: string;
  stopReason: string | null;
  instanceIp: string | null;
  port: number;
  updatedAt: string;
  repoOwner: string;
  repoName: string;
}

interface Stats {
  totalUsers: number;
  totalRepos: number;
  enabledRepos: number;
  totalPreviews: number;
  activePreviews: number;
  activeInstances: number;
  totalCostUsd: number;
  hourlyBurnUsd: number;
  byStatus: Record<string, number>;
  recentPreviews: RecentPreview[];
}

const STATUS_ORDER = ["RUNNING", "BUILDING", "PROVISIONING", "FAILED", "STOPPED", "IGNORED"];

function StatCard({
  icon: Icon,
  label,
  value,
  sub,
  delay,
}: {
  icon: LucideIcon;
  label: string;
  value: number | string;
  sub?: string;
  delay: number;
}) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay }}
      className="bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl p-4"
    >
      <div className="flex items-center gap-2 text-gray-500 dark:text-slate-400 mb-2">
        <Icon size={16} />
        <span className="text-xs font-medium uppercase tracking-wide">{label}</span>
      </div>
      <p className="text-3xl font-bold tabular-nums">{value}</p>
      {sub && <p className="text-xs text-gray-500 dark:text-slate-400 mt-1">{sub}</p>}
    </motion.div>
  );
}

export function Overview() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const { user } = useAuth();
  usePageTitle("Overview");

  const load = async () => {
    const res = await api.stats.get();
    if (res.ok) setStats(res.data || null);
    setLoading(false);
  };

  useEffect(() => { load(); }, []);
  useEffect(() => {
    const t = setInterval(load, 10000);
    return () => clearInterval(t);
  }, []);

  if (!user?.setupComplete && !loading) {
    return (
      <div className="text-center py-20">
        <Settings2 size={48} className="mx-auto mb-4 text-gray-400 dark:text-slate-500" />
        <h2 className="text-2xl font-bold mb-2">Setup Required</h2>
        <p className="text-gray-600 dark:text-slate-400 mb-6">Configure your Gitea and AWS credentials to get started.</p>
        <Link
          to="/settings"
          className="inline-flex px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition-colors"
        >
          Go to Settings
        </Link>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Overview</h1>
          <p className="text-sm text-gray-500 dark:text-slate-400">Instance-wide activity across PR Previews.</p>
        </div>
        <button onClick={load} className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline">
          <RefreshCw size={14} /> Refresh
        </button>
      </div>

      {loading ? (
        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="h-28 bg-gray-100 dark:bg-slate-800 rounded-xl animate-pulse" />
          ))}
        </div>
      ) : stats ? (
        <>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
            <StatCard icon={Rocket} label="Previews" value={stats.totalPreviews} sub={`${stats.activePreviews} active`} delay={0} />
            <StatCard icon={Server} label="Live Instances" value={stats.activeInstances} sub="running EC2s" delay={0.04} />
            <StatCard icon={FolderGit2} label="Repos" value={stats.totalRepos} sub={`${stats.enabledRepos} enabled`} delay={0.08} />
            <StatCard icon={Users} label="Users" value={stats.totalUsers} delay={0.12} />
            <StatCard
              icon={DollarSign}
              label="Est. Cost"
              value={formatUsd(stats.totalCostUsd)}
              sub={stats.hourlyBurnUsd > 0 ? `${formatUsd(stats.hourlyBurnUsd)}/hr now` : "no live spend"}
              delay={0.16}
            />
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* Status breakdown */}
            <div className="bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl p-4">
              <div className="flex items-center gap-2 mb-4">
                <Activity size={16} className="text-gray-500 dark:text-slate-400" />
                <h2 className="font-semibold">By status</h2>
              </div>
              {STATUS_ORDER.some(s => stats.byStatus[s]) ? (
                <ul className="space-y-2">
                  {STATUS_ORDER.filter(s => stats.byStatus[s]).map(s => (
                    <li key={s} className="flex items-center justify-between">
                      <StatusBadge status={s as any} />
                      <span className="text-sm font-medium tabular-nums">{stats.byStatus[s]}</span>
                    </li>
                  ))}
                </ul>
              ) : (
                <p className="text-sm text-gray-500 dark:text-slate-400">No previews yet.</p>
              )}
            </div>

            {/* Recent activity */}
            <div className="lg:col-span-2 bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl p-4">
              <div className="flex items-center justify-between mb-4">
                <h2 className="font-semibold">Recent activity</h2>
                <Link to="/previews" className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline">
                  All previews <ArrowRight size={14} />
                </Link>
              </div>
              {stats.recentPreviews.length === 0 ? (
                <p className="text-sm text-gray-500 dark:text-slate-400">
                  No previews yet. Enable a repo and open a pull request to get started.
                </p>
              ) : (
                <ul className="divide-y divide-gray-100 dark:divide-slate-700">
                  {stats.recentPreviews.map(p => (
                    <li key={p.id}>
                      <Link to={`/previews/${p.id}`} className="flex items-center justify-between gap-3 py-2.5 -mx-2 px-2 rounded-lg hover:bg-gray-50 dark:hover:bg-slate-700/40 transition-colors">
                        <div className="min-w-0">
                          <p className="text-xs text-gray-500 dark:text-slate-400 truncate">{p.repoOwner}/{p.repoName}</p>
                          <p className="text-sm font-medium truncate">PR #{p.prNumber}: {p.prTitle}</p>
                        </div>
                        <div className="flex items-center gap-3 shrink-0">
                          {p.status === "RUNNING" && p.instanceIp && (
                            <a
                              href={`http://${p.instanceIp}:${p.port}`}
                              target="_blank"
                              rel="noreferrer"
                              onClick={e => e.stopPropagation()}
                              className="hidden sm:inline-flex items-center gap-1 text-xs text-green-600 dark:text-green-400 hover:underline"
                            >
                              <ExternalLink size={12} /> open
                            </a>
                          )}
                          <StatusBadge status={p.status as any} reason={p.stopReason} />
                        </div>
                      </Link>
                    </li>
                  ))}
                </ul>
              )}
            </div>
          </div>
        </>
      ) : (
        <p className="text-sm text-gray-500 dark:text-slate-400">Failed to load stats.</p>
      )}
    </div>
  );
}
