import { useState, useMemo, useCallback } from "react";
import { useSettings } from "@/hooks/useSettings";
import { useCustomers } from "@/hooks/useCustomers";
import { useTransactions } from "@/hooks/useTransactions";
import { useFreelancers } from "@/hooks/useFreelancers";
import { useInvoices } from "@/hooks/useInvoices";
import { useTasks } from "@/hooks/useTasks";
import { getCurrencySymbol } from "../utils/currency";
import { DollarSign, TrendingUp, TrendingDown, Users, Briefcase, Download, BarChart3 } from "lucide-react";
import { format } from "date-fns";
import { useOwnerEmail } from "@/hooks/useOwnerEmail";
import { Button } from "@/components/ui/button";
import { getRangeCutoff, isInRange, RANGE_LABELS } from "@/lib/dashboardUtils";

import StatCard from "../components/dashboard/StatCard";
import RecentTransactions from "../components/dashboard/RecentTransactions";
import QuickActions from "../components/dashboard/QuickActions";
import SmartAlerts from "../components/dashboard/SmartAlerts";
import TimeRangeFilter from "../components/dashboard/TimeRangeFilter";
import RecentActivity from "../components/dashboard/RecentActivity";
import ForecastedRevenue from "../components/dashboard/ForecastedRevenue";
import ClientLTV from "../components/dashboard/ClientLTV";
import SaasMetrics from "../components/dashboard/SaasMetrics";
import IntersectionLoader from "../components/shared/IntersectionLoader";
import { SkeletonGrid } from "../components/shared/SkeletonCard";

const exportColumns = [
  { label: "Type",        accessor: (t) => t.type },
  { label: "Amount",      accessor: (t) => t.amount },
  { label: "Date",        accessor: (t) => t.date },
  { label: "Category",    accessor: (t) => t.category },
  { label: "Description", accessor: (t) => t.description || "" },
  { label: "Notes",       accessor: (t) => t.notes || "" },
];

function exportCSV(data, filename, columns) {
  if (!data?.length) return;
  const headers = columns.map((c) => c.label);
  const rows = data.map((row) =>
    columns.map((c) => {
      const val = String(c.accessor(row) ?? "");
      return val.includes(",") || val.includes('"') ? `"${val.replace(/"/g, '""')}"` : val;
    })
  );
  const csv = [headers.join(","), ...rows.map((r) => r.join(","))].join("\n");
  const blob = new Blob([csv], { type: "text/csv" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `${filename}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

function SectionLabel({ children }) {
  return (
    <p className="text-overline font-semibold text-[#8e9192] uppercase tracking-widest mb-3">{children}</p>
  );
}

function DashboardSkeleton() {
  return (
    <div className="p-4 md:p-6 space-y-5 w-full">
      <div className="flex justify-between items-center">
        <div className="animate-pulse h-6 w-32 bg-white/[0.04] rounded-lg" />
        <div className="animate-pulse h-8 w-48 bg-white/[0.04] rounded-lg" />
      </div>
      <SkeletonGrid count={6} />
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[...Array(4)].map((_, i) => <div key={i} className="animate-pulse h-28 bg-white/[0.02] rounded-xl" />)}
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
        <div className="lg:col-span-8 animate-pulse h-56 bg-white/[0.02] rounded-xl" />
        <div className="lg:col-span-4 space-y-3">
          {[...Array(3)].map((_, i) => <div key={i} className="animate-pulse h-[72px] bg-white/[0.02] rounded-xl" />)}
        </div>
      </div>
    </div>
  );
}



export default function Dashboard() {
  const [range, setRange] = useState("month");
  const { ownerEmail, isLoading: loadingOwner } = useOwnerEmail();

  // ─── Data fetches ──────────────────────────────────────────────────────────
  const { data: transactions = [], isLoading: loadingTx } = useTransactions();
  const { data: settings } = useSettings();
  const { data: allClients = [], isLoading: loadingCx } = useCustomers();
  const clients = allClients.filter(c => !c.archived);
  const { data: freelancers = [], isLoading: loadingFr } = useFreelancers();
  const { data: allInvoices = [], isLoading: loadingInv } = useInvoices();
  const { data: allTasks = [], isLoading: loadingTasks } = useTasks();

  // ─── Time range filtering ──────────────────────────────────────────────────
  const cutoff = useMemo(() => getRangeCutoff(range), [range]);

  const filteredTransactions = useMemo(() =>
    transactions.filter(t => isInRange(t.date, cutoff)),
    [transactions, cutoff]
  );

  const filteredInvoices = useMemo(() =>
    allInvoices.filter(i => isInRange(i.issued_date || i.created_date, cutoff)),
    [allInvoices, cutoff]
  );

  // ─── KPI metrics ───────────────────────────────────────────────────────────
  const currency = settings?.currency || "USD";
  const sym = getCurrencySymbol(currency);

  const revenueStats = useMemo(() => {
    const paidInvoices = allInvoices.filter(i =>
      i.status === "paid" && isInRange(i.paid_date || i.issued_date || i.created_date, cutoff)
    );
    const actualRevenue = paidInvoices.reduce((s, i) => s + (i.total || 0), 0);

    const mrr = allInvoices
      .filter(i => i.status === "paid" && i.invoice_type === "client" && isInRange(i.paid_date || i.issued_date || i.created_date, getRangeCutoff("month")))
      .reduce((s, i) => s + (i.total || 0), 0);

    const projectedRevenue = allInvoices
      .filter(i => ["submitted", "sent"].includes(i.status))
      .reduce((s, i) => s + (i.total || 0), 0);

    const expenses = filteredTransactions
      .filter(t => t.type === "expense")
      .reduce((s, t) => s + (t.amount || 0), 0);

    const hasExpenses = filteredTransactions.some(t => t.type === "expense");

    return { actualRevenue, mrr, projectedRevenue, expenses, hasExpenses, netProfit: actualRevenue - expenses };
  }, [allInvoices, filteredTransactions, cutoff]);

  const peopleStats = useMemo(() => {
    const clientsWithTask    = new Set(allTasks.filter(t => t.status !== "done" && !t.archived && t.client_id).map(t => t.client_id));
    const clientsWithInvoice = new Set(allInvoices.filter(i => ["submitted", "sent", "paid"].includes(i.status) && i.client_id).map(i => i.client_id));
    const activeClients      = clients.filter(c => new Set([...clientsWithTask, ...clientsWithInvoice]).has(c.id)).length;

    const freelancerWithTask = new Set(allTasks.filter(t => t.status !== "done" && !t.archived && t.freelancer_id).map(t => t.freelancer_id));
    const activeFreelancers  = freelancers.filter(f => freelancerWithTask.has(f.id)).length;

    return { activeClients, activeFreelancers };
  }, [clients, freelancers, allTasks, allInvoices]);

  const isLoading = loadingOwner || loadingTx || loadingCx || loadingFr || loadingInv || loadingTasks;

  const handleExport = useCallback(() => {
    exportCSV(filteredTransactions, `dashboard-${format(new Date(), "yyyy-MM-dd")}`, exportColumns);
  }, [filteredTransactions]);

  if (isLoading) return <DashboardSkeleton />;

  return (
    <div className="p-4 md:p-5 w-full space-y-4 overflow-x-hidden">

      {/* ── HEADER ── */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <div>
          <h1 className="text-h4 font-bold text-white tracking-tight">Dashboard</h1>
          <p className="text-caption text-[#8e9192] mt-0.5">Overview · {RANGE_LABELS[range]}</p>
        </div>
        <div className="flex items-center gap-2 flex-wrap">
          <QuickActions />
          <TimeRangeFilter active={range} onChange={setRange} />
          <Button variant="outline" size="sm" onClick={handleExport} className="gap-1.5 text-[#c4c7c8] border-[#2D2D2D] h-8">
            <Download className="w-3.5 h-3.5" />
            <span className="hidden sm:inline text-caption">Export</span>
          </Button>
        </div>
      </div>

      {/* ── Smart Alerts ── */}
      <SmartAlerts tasks={allTasks} invoices={allInvoices} clients={clients} currencySymbol={sym} />

      {/* ── ROW 1: EXECUTIVE METRICS (6 cards) ── */}
      <div>
        <SectionLabel>Executive Metrics</SectionLabel>
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3">
          <StatCard title="Revenue" value={sym + revenueStats.actualRevenue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} icon={DollarSign} accent="indigo" />
          <StatCard title="MRR" value={sym + revenueStats.mrr.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} icon={BarChart3} accent="violet" />
          <StatCard title="Projected" value={sym + revenueStats.projectedRevenue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} icon={TrendingUp} accent="emerald" />
          <StatCard title="Net Profit" value={revenueStats.hasExpenses ? sym + revenueStats.netProfit.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : "—"} icon={TrendingDown} accent={revenueStats.netProfit >= 0 ? "emerald" : "rose"} />
          <StatCard title="Active Clients" value={peopleStats.activeClients} icon={Users} accent="amber" />
          <StatCard title="Freelancers" value={peopleStats.activeFreelancers} icon={Briefcase} accent="violet" />
        </div>
      </div>

      {/* ── ROW 2: SAAS HEALTH METRICS (4 cards) ── */}
      <div className="rounded-xl border border-white/15 bg-white/[0.03] p-4">
        <SaasMetrics invoices={allInvoices} tasks={allTasks} clients={clients} currencySymbol={sym} range={range} />
      </div>

      {/* ── ROW 5: BUSINESS INSIGHTS — 6/6 ── */}
      <IntersectionLoader skeleton={<div className="animate-pulse h-40 bg-white/[0.02] rounded-xl" />} minHeight="160px">
        <div>
          <SectionLabel>Business Insights</SectionLabel>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <ForecastedRevenue invoices={allInvoices} currencySymbol={sym} />
            <ClientLTV invoices={allInvoices} currencySymbol={sym} />
          </div>
        </div>
      </IntersectionLoader>

      {/* ── ROW 6: ACTIVITY — 7/5 ── */}
      <IntersectionLoader skeleton={<div className="animate-pulse h-48 bg-white/[0.02] rounded-xl" />} minHeight="200px">
        <div>
          <SectionLabel>Activity</SectionLabel>
          <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
            <div className="lg:col-span-7 min-w-0">
              <RecentActivity />
            </div>
            <div className="lg:col-span-5 min-w-0">
              <RecentTransactions data={filteredTransactions} />
            </div>
          </div>
        </div>
      </IntersectionLoader>



    </div>
  );
}