"use client";

import { useMemo } from "react";
import { RefreshCw } from "lucide-react";
import { columns } from "@/components/datatable/overallsummary/columns";
import { DataTable } from "@/components/datatable/data-table";
import { PageHeader } from "@/components/ui/PageHeader";
import { ErrorMessage } from "@/components/ui/ErrorMessage";
import { useOverallSummaryReport } from "@/hooks/useOverallSummaryReport";
import { OverallSummaryStatCards } from "@/components/reports/overallsummary/OverallSummaryStatCards";
import { calculateStats } from "@/utils/overall-summary-utils";

const actionButtonClass = (disabled: boolean) =>
  disabled
    ? "inline-flex items-center gap-2 rounded-lg border border-gray-200 bg-gray-100 px-3 py-1.5 text-xs font-medium text-gray-500 shadow-sm transition-all duration-200 cursor-not-allowed"
    : "inline-flex items-center gap-2 rounded-lg border border-[#428B4D]/40 bg-white px-3 py-1.5 text-xs font-semibold text-slate-700 shadow-sm transition-all duration-200 hover:-translate-y-0.5 hover:border-[#428B4D] hover:bg-[#428B4D] hover:text-white focus:outline-none focus-visible:ring-2 focus-visible:ring-[#428B4D]/40 active:scale-95";

export default function OverallSummary() {
  const { data, loading, error, lastRefreshedAt, loadData } = useOverallSummaryReport();

  const stats = useMemo(() => calculateStats(data), [data]);

  if (loading && !data.length) {
    return (
      <div className="container mx-auto px-4 py-10">
        <PageHeader
          title="Overall Summary"
          description="Consolidated view of every holding across asset classes with up-to-date performance."
          breadcrumbs={[
            { label: "Home", href: "/" },
            { label: "Reports" },
            { label: "Performance" },
            { label: "Overall Summary" },
          ]}
          actions={
            <div className="flex items-center gap-3 text-right">
              <button onClick={loadData} disabled className={actionButtonClass(true)}>
                <RefreshCw className="h-4 w-4 animate-spin" />
                Refreshing...
              </button>
            </div>
          }
        />

        <div className="mt-10 flex h-64 items-center justify-center">
          <RefreshCw className="h-10 w-10 animate-spin text-[#428B4D]" />
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-10">
      <PageHeader
        title="Overall Summary"
        description="Consolidated view of every holding across asset classes with up-to-date performance."
        breadcrumbs={[
          { label: "Home", href: "/" },
          { label: "Reports" },
          { label: "Performance" },
          { label: "Overall Summary" },
        ]}
        actions={
          <div className="flex items-center gap-3 text-right">
            {lastRefreshedAt && (
              <span className="text-xs text-slate-500">
                Last refreshed: {new Date(lastRefreshedAt).toLocaleString()}
              </span>
            )}
            <button onClick={loadData} disabled={loading} className={actionButtonClass(loading)}>
              <RefreshCw className={loading ? "h-4 w-4 animate-spin" : "h-4 w-4"} />
              {loading ? "Refreshing..." : "Refresh"}
            </button>
          </div>
        }
      />

      {/* Error Message */}
      {error && (
        <ErrorMessage
          error={error}
          onDismiss={() => {}}
          className="mt-6"
        />
      )}

      <OverallSummaryStatCards stats={stats} loading={loading} />

      <div className="mt-8 space-y-3">
        <div className="flex items-center justify-between">
          <h2 className="text-lg font-semibold text-slate-800">Report Detail</h2>
          <span className="text-xs font-medium text-slate-500">
            {loading ? "Loading latest data…" : `${stats.holdings.toLocaleString()} records`}
          </span>
        </div>
        <div className="rounded-lg">
          {loading ? (
            <div className="flex items-center justify-center rounded-lg border border-slate-200 bg-white py-14 shadow-sm">
              <div className="flex items-center gap-2 text-sm font-medium text-slate-600">
                <RefreshCw className="h-5 w-5 animate-spin text-[#428B4D]" />
                Loading latest data…
              </div>
            </div>
          ) : null}
          <DataTable columns={columns} data={Array.isArray(data) ? data : []} />
        </div>
      </div>
    </div>
  );
}
