"use client";

import type { AuditLogEntry, BulkJob, DashboardStats, ServerGroup } from "@domainops/shared-types";
import { App, Button, Card, Progress, Statistic, Table, Tag, Typography } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { getDashboardStats } from "@/lib/api/dashboard";
import { renewDomain } from "@/lib/api/domains";
import { listAuditLog } from "@/lib/api/audit";
import { listSeoBulkJobs } from "@/lib/api/bulkSeo";
import { listServerGroups } from "@/lib/api/servers";
import { ApiError } from "@/lib/api/client";
import { titleCase } from "@/lib/utils/text";
import { formatDate } from "@/lib/utils/date";
import { expiryInfo } from "@/lib/utils/expiry";

const HEALTH_COLORS: Record<ServerGroup["health_status"], string> = {
  healthy: "green",
  degraded: "orange",
  unknown: "default",
};

const TLD_COLORS = ["#101623", "#2F4BEA", "#5B6BEF", "#0C8A5F", "#22A87B", "#B45309", "#D97A2B", "#6D3FC4"];

const WIZARD_STEPS = [
  { step: 1, title: "Buy Domains", description: "Paste names, check pricing, and buy them for you.", href: "/acquire" },
  { step: 2, title: "Put Them On A Server", description: "Pick domains, pick a server. No DNS knowledge needed.", href: "/servers" },
  { step: 3, title: "Make A Site Live", description: "Upload a ZIP or install WordPress in one click.", href: "/domains" },
  { step: 4, title: "Redirect A Domain", description: "Send an old domain to a new one, recorded automatically.", href: "/redirects" },
];

export default function DashboardHomePage() {
  const { message } = App.useApp();
  const router = useRouter();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [jobs, setJobs] = useState<BulkJob[]>([]);
  const [activity, setActivity] = useState<AuditLogEntry[]>([]);
  const [serverGroups, setServerGroups] = useState<ServerGroup[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [renewingId, setRenewingId] = useState<number | null>(null);

  const load = useCallback(async () => {
    setIsLoading(true);
    try {
      const [statsResult, jobsResult, activityResult, groupsResult] = await Promise.all([
        getDashboardStats(),
        listSeoBulkJobs(),
        listAuditLog({}),
        listServerGroups(),
      ]);
      setStats(statsResult);
      setJobs(jobsResult.filter((job) => job.state !== "finished"));
      setActivity(activityResult.data.slice(0, 6));
      setServerGroups(groupsResult);
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't load the dashboard.");
    } finally {
      setIsLoading(false);
    }
  }, [message]);

  useEffect(() => {
    // Dashboard data lives on the Laravel API - a client fetch on mount,
    // not a state-sync bug.
    // eslint-disable-next-line react-hooks/set-state-in-effect
    void load();
  }, [load]);

  async function handleRenew(domainId: number) {
    setRenewingId(domainId);
    try {
      await renewDomain(domainId);
      message.success("Renewal submitted.");
      void load();
    } catch (err) {
      message.error(err instanceof ApiError ? err.message : "Couldn't renew that domain.");
    } finally {
      setRenewingId(null);
    }
  }

  const tldTotal = stats?.by_tld.reduce((sum, row) => sum + row.count, 0) ?? 0;

  const expiringColumns: ColumnsType<DashboardStats["expiring"][number]> = [
    { title: "Domain", dataIndex: "fqdn", render: (v: string) => <span className="font-mono">{v}</span> },
    { title: "Registrar", dataIndex: "registrar_label", render: (v: string | null) => v ?? "—" },
    { title: "Expires", dataIndex: "expires_at", render: (v: string | null) => formatDate(v) },
    {
      title: "Time Left",
      dataIndex: "expires_at",
      render: (v: string | null) => {
        const info = expiryInfo(v);

        return info ? (
          <span className="font-medium" style={{ color: info.color }}>
            {info.label || `${info.daysLeft} days left`}
          </span>
        ) : (
          "—"
        );
      },
    },
    {
      title: "",
      render: (_, row) => (
        <Button
          size="small"
          loading={renewingId === row.id}
          onClick={() => handleRenew(row.id)}
          className="dms_dashboard_renew_domain_btn"
        >
          Renew
        </Button>
      ),
    },
  ];

  const activityColumns: ColumnsType<AuditLogEntry> = [
    { title: "When", dataIndex: "created_at", render: (v: string) => new Date(v).toLocaleString() },
    { title: "Action", dataIndex: "action", render: (v: string) => v.replace(/_/g, " ") },
    { title: "By", render: (_, entry) => entry.actor?.name ?? "System" },
  ];

  const serverColumns: ColumnsType<ServerGroup> = [
    { title: "Label", dataIndex: "label", render: (v: string) => <span className="font-semibold">{v}</span> },
    {
      title: "Health",
      dataIndex: "health_status",
      render: (v: ServerGroup["health_status"]) => <Tag color={HEALTH_COLORS[v]}>{titleCase(v)}</Tag>,
    },
    { title: "Accounts", dataIndex: "accounts_count", render: (v: number | undefined) => v ?? 0 },
    { title: "Static Capacity", dataIndex: "capacity_static", render: (v: number | null) => v ?? "—" },
    { title: "WordPress Capacity", dataIndex: "capacity_wp", render: (v: number | null) => v ?? "—" },
  ];

  return (
    <div className="flex flex-col gap-4 page page-dashboard">
      <div className="flex items-center justify-between">
        <div>
          <Typography.Text type="secondary" className="uppercase text-xs tracking-wide">
            Portfolio
          </Typography.Text>
          <Typography.Title level={4} style={{ margin: 0 }}>
            Dashboard
          </Typography.Title>
          <Typography.Paragraph type="secondary" style={{ marginBottom: 0 }}>
            One console for the full domain lifecycle - buy, point, deploy, redirect, retire.
          </Typography.Paragraph>
        </div>
        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => router.push("/acquire")}
          className="dms_dashboard_buy_domains_btn"
        >
          Buy Domains
        </Button>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
        {WIZARD_STEPS.map((item) => (
          <Card key={item.step} hoverable onClick={() => router.push(item.href)} className="cursor-pointer">
            <div className="flex items-start gap-3">
              <div className="flex items-center justify-center w-7 h-7 rounded-full bg-black/10 font-semibold shrink-0">
                {item.step}
              </div>
              <div>
                <div className="font-semibold">{item.title}</div>
                <div className="text-xs text-gray-500">{item.description}</div>
              </div>
            </div>
          </Card>
        ))}
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
        <Card loading={isLoading}>
          <Statistic title="Total Domains" value={stats?.total ?? 0} />
        </Card>
        <Card loading={isLoading}>
          <Statistic title="Live" value={stats?.live ?? 0} styles={{ content: { color: "#0C8A5F" } }} />
        </Card>
        <Card loading={isLoading}>
          <Statistic title="Redirected" value={stats?.redirected ?? 0} />
        </Card>
        <Card loading={isLoading}>
          <Statistic title="Parked" value={stats?.parked ?? 0} />
        </Card>
        <Card loading={isLoading}>
          <Statistic title="Expiring ≤30 Days" value={stats?.expiring_soon ?? 0} styles={{ content: { color: "#B45309" } }} />
        </Card>
        <Card loading={isLoading}>
          <Statistic title="Added This Month" value={stats?.added_this_month ?? 0} />
        </Card>
      </div>

      <Card title="Bulk Jobs Running" loading={isLoading} className="dms_dashboard_bulk_jobs_card">
        {jobs.length === 0 ? (
          <Typography.Text type="secondary">Nothing running right now.</Typography.Text>
        ) : (
          <div className="flex flex-col gap-3">
            {jobs.map((job) => (
              <div key={job.id}>
                <div className="flex justify-between text-sm mb-1">
                  <span className="font-medium">{job.kind.replace(/[._]/g, " ")}</span>
                  <span className="text-gray-500">
                    {job.done}/{job.total}
                  </span>
                </div>
                <Progress percent={job.total ? Math.round((job.done / job.total) * 100) : 0} size="small" />
              </div>
            ))}
          </div>
        )}
      </Card>

      <Card title="Inventory By TLD" loading={isLoading}>
        <div className="flex h-3 rounded overflow-hidden mb-3">
          {stats?.by_tld.map((row, index) => (
            <div
              key={row.tld}
              style={{ width: `${tldTotal ? (row.count / tldTotal) * 100 : 0}%`, background: TLD_COLORS[index % TLD_COLORS.length] }}
              title={`${row.tld} - ${row.count}`}
            />
          ))}
        </div>
        <div className="flex flex-wrap gap-4 text-xs">
          {stats?.by_tld.map((row, index) => (
            <span key={row.tld} className="flex items-center gap-1.5">
              <i
                className="inline-block w-2.5 h-2.5 rounded-sm"
                style={{ background: TLD_COLORS[index % TLD_COLORS.length] }}
              />
              {row.tld} {row.count}
            </span>
          ))}
        </div>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        <Card title="Expiring Soon" loading={isLoading} className="dms_dashboard_expiring_soon_card">
          <Table
            rowKey="id"
            size="small"
            pagination={false}
            columns={expiringColumns}
            dataSource={stats?.expiring ?? []}
            className="dms_dashboard_expiring_soon_table"
          />
        </Card>

        <Card title="Recent Activity" loading={isLoading} className="dms_dashboard_recent_activity_card">
          <Table
            rowKey="id"
            size="small"
            pagination={false}
            columns={activityColumns}
            dataSource={activity}
            className="dms_dashboard_recent_activity_table"
          />
        </Card>
      </div>

      <Card title="Server Fleet" loading={isLoading} className="dms_dashboard_server_fleet_card">
        <Table
          rowKey="id"
          size="small"
          pagination={false}
          columns={serverColumns}
          dataSource={serverGroups}
          className="dms_dashboard_server_fleet_table"
        />
      </Card>
    </div>
  );
}
