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, Search, RefreshCw, ArrowRight, ExternalLink, ChevronDown, ChevronRight } from "lucide-react";

interface Preview {
  id: number;
  prNumber: number;
  prTitle: string;
  commitSha: string;
  status: string;
  stopReason: string | null;
  instanceIp: string | null;
  port: number;
  createdAt: string;
  updatedAt: string;
  lastActivityAt: string;
  repoOwner: string;
  repoName: string;
  instanceType: string | null;
  costUsd: number;
}

// Previews still doing something get shown by default; the rest are tucked away.
const ACTIVE_STATUSES = ["PROVISIONING", "BUILDING", "RUNNING"];

function PreviewCard({ p, i }: { p: Preview; i: number }) {
  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: Math.min(i * 0.04, 0.4) }}
    >
      <Link
        to={`/previews/${p.id}`}
        className="block bg-white dark:bg-slate-800 border border-gray-200 dark:border-slate-700 rounded-xl p-4 hover:shadow-md hover:border-blue-300 dark:hover:border-blue-600 transition-all"
      >
        <div className="flex items-start justify-between mb-2">
          <div>
            <p className="text-xs text-gray-500 dark:text-slate-400">{p.repoOwner}/{p.repoName}</p>
            <p className="font-semibold text-sm mt-0.5 line-clamp-1">PR #{p.prNumber}: {p.prTitle}</p>
          </div>
          <StatusBadge status={p.status as any} reason={p.stopReason} />
        </div>

        <p className="text-xs text-gray-500 dark:text-slate-400 mb-2">
          Commit: <code className="bg-gray-100 dark:bg-slate-700 px-1 rounded">{p.commitSha.slice(0, 8)}</code>
        </p>

        {p.status === "RUNNING" && p.instanceIp && (
          <a
            href={`http://${p.instanceIp}:${p.port}`}
            target="_blank"
            rel="noreferrer"
            onClick={e => e.stopPropagation()}
            className="inline-flex items-center gap-1 text-xs text-green-600 dark:text-green-400 hover:underline"
          >
            <ExternalLink size={12} /> http://{p.instanceIp}:{p.port}
          </a>
        )}

        <div className="flex items-center justify-between mt-2">
          <p className="text-xs text-gray-400 dark:text-slate-500">
            Updated {new Date(p.updatedAt).toLocaleString()}
          </p>
          <span className="text-xs font-medium text-gray-500 dark:text-slate-400 tabular-nums" title="Estimated EC2 cost">
            {formatUsd(p.costUsd)}
          </span>
        </div>
      </Link>
    </motion.div>
  );
}

export function Dashboard() {
  const [previews, setPreviews] = useState<Preview[]>([]);
  const [loading, setLoading] = useState(true);
  const [showOld, setShowOld] = useState(false);
  const { user } = useAuth();
  usePageTitle("Previews");

  const load = async () => {
    const res = await api.previews.list();
    if (res.ok) setPreviews(res.data || []);
    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>
    );
  }

  const active = previews.filter(p => ACTIVE_STATUSES.includes(p.status));
  const old = previews.filter(p => !ACTIVE_STATUSES.includes(p.status));
  const totalCost = previews.reduce((sum, p) => sum + (p.costUsd || 0), 0);

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold">Previews</h1>
          {previews.length > 0 && (
            <p className="text-sm text-gray-500 dark:text-slate-400">
              Estimated total EC2 cost: <span className="font-medium text-gray-700 dark:text-slate-200">{formatUsd(totalCost)}</span>
            </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-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="h-40 bg-gray-100 dark:bg-slate-800 rounded-xl animate-pulse" />
          ))}
        </div>
      ) : previews.length === 0 ? (
        <div className="text-center py-20">
          <Search size={48} className="mx-auto mb-4 text-gray-400 dark:text-slate-500" />
          <h2 className="text-xl font-semibold mb-2">No previews yet</h2>
          <p className="text-gray-500 dark:text-slate-400 mb-4">
            Enable a repo and open a pull request to create your first preview.
          </p>
          <Link to="/repos" className="inline-flex items-center gap-1 text-blue-600 dark:text-blue-400 hover:underline">
            Configure repos <ArrowRight size={14} />
          </Link>
        </div>
      ) : (
        <>
          {active.length > 0 ? (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {active.map((p, i) => <PreviewCard key={p.id} p={p} i={i} />)}
            </div>
          ) : (
            <div className="text-center py-12 border border-dashed border-gray-200 dark:border-slate-700 rounded-xl">
              <p className="text-gray-500 dark:text-slate-400">No active previews right now.</p>
            </div>
          )}

          {old.length > 0 && (
            <div className="mt-8">
              <button
                onClick={() => setShowOld(v => !v)}
                className="inline-flex items-center gap-1.5 text-sm font-medium text-gray-600 dark:text-slate-300 hover:text-gray-900 dark:hover:text-white transition-colors"
              >
                {showOld ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
                {showOld ? "Hide" : "Show"} stopped &amp; old previews ({old.length})
              </button>

              {showOld && (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4">
                  {old.map((p, i) => <PreviewCard key={p.id} p={p} i={i} />)}
                </div>
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
