"use client";

import Link from "next/link";
import { useLang } from "@/context/LanguageContext";
import { Card, EmptyState, PageLoader, StatCard } from "@/components/ui";
import { useApi } from "@/lib/client";
import { formatBDT, formatDate } from "@/lib/utils";
import {
  IconAcademic,
  IconBuilding,
  IconCard,
  IconClipboard,
  IconPackage,
  IconTrend,
  IconWallet,
} from "@/components/icons";

interface Stats {
  totalInstitutions: number;
  pendingInstitutions: number;
  activeSubscriptions: number;
  pendingRequests: number;
  totalPlans: number;
  totalAcademicItems: number;
  totalCollected: number;
  totalDue: number;
  monthly: { key: string; label: string; total: number }[];
  recentPayments: {
    id: number;
    invoiceNo: string;
    amount: string;
    method: string;
    paidAt: string;
    institution: { name: string };
  }[];
}

export default function CentralDashboard() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<Stats>("/api/central/stats");

  if (loading) return <PageLoader text={t.common.loading} />;
  if (!data) return <EmptyState title={t.common.tryAgain} />;

  const maxMonthly = Math.max(1, ...data.monthly.map((m) => m.total));

  return (
    <div>
      <div className="row mb-4">
        <div className="col-12">
          <h4 className="f-w-700 mb-1">{t.central.dashboard.title}</h4>
          <p className="text-muted mb-0 ems-fs-13">{t.central.dashboard.welcome} 👋</p>
        </div>
      </div>

      {/* Stat cards */}
      <div className="row g-4 mb-2">
        <div className="col-xl-3 col-md-6">
          <StatCard
            label={t.central.dashboard.totalInstitutions}
            value={String(data.totalInstitutions)}
            icon={<IconBuilding />}
            accent="teal"
            hint={`${data.pendingInstitutions} ${t.central.dashboard.pendingInstitutions}`}
          />
        </div>
        <div className="col-xl-3 col-md-6">
          <StatCard
            label={t.central.dashboard.activeSubscriptions}
            value={String(data.activeSubscriptions)}
            icon={<IconPackage />}
            accent="blue"
          />
        </div>
        <div className="col-xl-3 col-md-6">
          <StatCard
            label={t.central.dashboard.pendingRequests}
            value={String(data.pendingRequests)}
            icon={<IconClipboard />}
            accent="orange"
          />
        </div>
        <div className="col-xl-3 col-md-6">
          <StatCard
            label={t.central.dashboard.totalCollected}
            value={formatBDT(data.totalCollected, locale)}
            icon={<IconWallet />}
            accent="purple"
            hint={`${t.central.dashboard.totalDue}: ${formatBDT(data.totalDue, locale)}`}
          />
        </div>
      </div>

      <div className="row g-4 mb-2">
        {/* Revenue chart */}
        <div className="col-xl-8">
          <Card title={t.central.dashboard.revenueTrend} icon={<IconTrend className="svg-20" />}>
            <div className="d-flex align-items-end gap-3" style={{ height: 190 }}>
              {data.monthly.map((m) => (
                <div className="flex-fill text-center" key={m.key}>
                  <p className="ems-fs-11 f-w-700 text-muted mb-1">{m.total > 0 ? formatBDT(m.total, locale) : ""}</p>
                  <div className="ems-bar" style={{ height: `${Math.max(4, (m.total / maxMonthly) * 100)}%` }} />
                  <p className="ems-fs-12 f-w-600 text-muted mt-2 mb-0">{m.label}</p>
                </div>
              ))}
            </div>
          </Card>
        </div>

        {/* Quick actions */}
        <div className="col-xl-4">
          <Card title={t.central.dashboard.quickActions}>
            <div className="d-flex flex-column gap-2">
              <Link href="/central/academic" className="media align-items-center gap-3 p-3 rounded" style={{ background: "rgba(36,105,92,0.08)" }}>
                <span className="ems-stat-icon teal"><IconAcademic /></span>
                <div className="media-body">
                  <h6 className="mb-0 f-w-700 ems-fs-13">{t.common.academicInfo}</h6>
                  <p className="mb-0 ems-fs-11 text-muted">{data.totalAcademicItems} {t.central.dashboard.academicItems}</p>
                </div>
              </Link>
              <Link href="/central/packages" className="media align-items-center gap-3 p-3 rounded" style={{ background: "rgba(34,126,230,0.08)" }}>
                <span className="ems-stat-icon blue"><IconPackage /></span>
                <div className="media-body">
                  <h6 className="mb-0 f-w-700 ems-fs-13">{t.central.packages.title}</h6>
                  <p className="mb-0 ems-fs-11 text-muted">{data.totalPlans} {t.central.dashboard.packagePlans}</p>
                </div>
              </Link>
              <Link href="/central/payments" className="media align-items-center gap-3 p-3 rounded" style={{ background: "rgba(247,154,27,0.1)" }}>
                <span className="ems-stat-icon orange"><IconCard /></span>
                <div className="media-body">
                  <h6 className="mb-0 f-w-700 ems-fs-13">{t.central.paymentsPage.title}</h6>
                  <p className="mb-0 ems-fs-11 text-muted">{formatBDT(data.totalDue, locale)} {t.common.due}</p>
                </div>
              </Link>
            </div>
          </Card>
        </div>
      </div>

      {/* Recent payments */}
      <div className="row">
        <div className="col-12">
          <Card
            title={t.central.dashboard.recentPayments}
            icon={<IconCard className="svg-20" />}
            action={
              <Link href="/central/payments" className="ems-text-teal f-w-700 text-decoration-none ems-fs-13">
                {t.common.viewAll} →
              </Link>
            }
          >
            {data.recentPayments.length === 0 ? (
              <EmptyState icon={<IconCard />} title={t.central.dashboard.noPayments} />
            ) : (
              <div className="table-responsive">
                <table className="table table-hover align-middle mb-0">
                  <thead className="ems-table-head">
                    <tr>
                      <th>{t.central.paymentsPage.invoiceNo}</th>
                      <th>{t.common.institution}</th>
                      <th>{t.common.method}</th>
                      <th>{t.common.date}</th>
                      <th className="text-end">{t.common.amount}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {data.recentPayments.map((p) => (
                      <tr key={p.id}>
                        <td>
                          <span className="ems-invoice-badge">
                            {p.invoiceNo}
                          </span>
                        </td>
                        <td className="f-w-600">{p.institution.name}</td>
                        <td>
                          <span className="badge badge-secondary">
                            {t.methods[p.method as keyof typeof t.methods]}
                          </span>
                        </td>
                        <td className="ems-fs-12 text-muted">{formatDate(p.paidAt, locale)}</td>
                        <td className="text-end f-w-800 text-success">{formatBDT(p.amount, locale)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
}
