"use client";
// src/app/reports/page.tsx
import { useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/layout/AppShell";
import { Card, CardHeader, CardTitle, CardContent, StatCard } from "@/components/ui/index";
import {
  formatCurrency,
  DEAL_STAGE_LABELS,
  DEAL_STAGE_LABELS_AR,
  getLabel,
  LEAD_SOURCE_LABELS,
  LEAD_SOURCE_LABELS_AR,
} from "@/lib/utils";
import { DEAL_STAGE_CHART_COLORS } from "@/lib/chartColors";
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
  PieChart, Pie, Cell, Legend,
} from "recharts";
import { Loader2, TrendingUp, Users, DollarSign, Briefcase, FileText, Receipt } from "lucide-react";
import { useLanguage } from "@/i18n/LanguageContext";

const COLORS = ["#3b82f6", "#8b5cf6", "#f59e0b", "#10b981", "#ef4444", "#06b6d4", "#f97316", "#ec4899"];

export default function ReportsPage() {
  const { t, language, isRTL } = useLanguage();
  const [data, setData] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetch("/api/dashboard")
      .then((r) => r.json())
      .then((d) => setData(d.data))
      .catch(console.error)
      .finally(() => setIsLoading(false));
  }, []);

  const stats = data?.stats ?? {};
  const dealsByStage = data?.dealsByStage;
  const dealsByStageList = dealsByStage ?? [];
  const dealsStageSummary = useMemo(() => {
    const rows = dealsByStage ?? [];
    const count = rows.reduce((s: number, r: { count: number }) => s + r.count, 0);
    const value = rows.reduce((s: number, r: { value: number }) => s + Number(r.value ?? 0), 0);
    return { count, value };
  }, [dealsByStage]);
  const leadsLastSixMonths = data?.leadsLastSixMonths ?? [];
  const leadsBySource = data?.leadsBySource;

  const leadSourceChartData = useMemo(() => {
    const rows = (leadsBySource ?? []).map((r: { source: string; count: number }) => ({
      name: getLabel(LEAD_SOURCE_LABELS, LEAD_SOURCE_LABELS_AR, r.source, language),
      value: r.count,
      rawSource: r.source,
    }));
    const total = rows.reduce((s: number, r: { value: number }) => s + r.value, 0) || 1;
    return rows.map((r: { name: string; value: number }) => ({
      ...r,
      pct: Math.round((r.value / total) * 100),
    }));
  }, [leadsBySource, language]);

  const conversionFunnel = useMemo(() => {
    const byStatus: Record<string, number> = {};
    for (const row of data?.leadsByStatus ?? []) {
      byStatus[row.status] = row.count;
    }
    return [
      { label: t("reports.funnelTotalLeads"), count: stats.totalLeads ?? 0 },
      { label: t("leads.statusCONTACTED"), count: byStatus.CONTACTED ?? 0 },
      { label: t("leads.statusQUALIFIED"), count: byStatus.QUALIFIED ?? 0 },
      { label: t("leads.statusCONVERTED"), count: byStatus.CONVERTED ?? 0 },
      { label: t("reports.funnelWonDeals"), count: stats.wonDeals ?? 0 },
    ];
  }, [data?.leadsByStatus, stats.totalLeads, stats.wonDeals, t]);

  if (isLoading) {
    return (
      <AppShell breadcrumbs={[{ label: t("reports.title") }]}>
        <div className="flex items-center justify-center h-64">
          <Loader2 className="w-8 h-8 animate-spin text-primary" />
        </div>
      </AppShell>
    );
  }

  const locale = language === "ar" ? "ar-SA" : "en-US";

  return (
    <AppShell breadcrumbs={[{ label: t("reports.title") }]}>
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">{t("reports.title")}</h1>
        <p className="text-sm text-muted-foreground mt-0.5">{t("reports.subtitle")}</p>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard
          title={t("dashboard.cardTotalLeads")}
          value={stats.totalLeads ?? 0}
          change={t("dashboard.thisMonth", { count: stats.newLeadsThisMonth ?? 0 })}
          changeType="up"
          icon={<TrendingUp className="w-5 h-5 text-blue-600" />}
          iconBg="bg-blue-100"
        />
        <StatCard
          title={t("dashboard.totalCustomers")}
          value={stats.totalCustomers ?? stats.totalContacts ?? 0}
          change={t("dashboard.conversionRateChange", { rate: stats.conversionRate ?? 0 })}
          changeType="neutral"
          icon={<Users className="w-5 h-5 text-green-600" />}
          iconBg="bg-green-100"
        />
        <StatCard
          title={t("dashboard.totalRevenue")}
          value={formatCurrency(stats.totalRevenue ?? 0)}
          change={t("dashboard.revenueYearLabel")}
          changeType="up"
          icon={<DollarSign className="w-5 h-5 text-emerald-600" />}
          iconBg="bg-emerald-100"
        />
        <StatCard
          title={t("dashboard.cardActiveDeals")}
          value={stats.totalDeals ?? stats.totalOpportunities ?? 0}
          change={t("dashboard.closedWonCount", { count: stats.wonDeals ?? 0 })}
          changeType="up"
          icon={<Briefcase className="w-5 h-5 text-purple-600" />}
          iconBg="bg-purple-100"
        />
      </div>

      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        <StatCard
          title={t("nav.quotes")}
          value={stats.quotesTotal ?? 0}
          change={t("reports.quotesInSystem")}
          changeType="neutral"
          icon={<FileText className="w-5 h-5 text-sky-600" />}
          iconBg="bg-sky-100"
        />
        <StatCard
          title={t("nav.invoices")}
          value={stats.invoicesTotal ?? 0}
          change={t("reports.invoicesInSystem")}
          changeType="neutral"
          icon={<Receipt className="w-5 h-5 text-amber-600" />}
          iconBg="bg-amber-100"
        />
      </div>

      {/* Charts Row 1 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <Card>
          <CardHeader>
            <CardTitle>{t("dashboard.chartLeadsSixMonths")}</CardTitle>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={240}>
              <BarChart data={leadsLastSixMonths} margin={{ top: 0, right: 0, left: -20, bottom: 0 }}>
                <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" />
                <XAxis
                  dataKey="month"
                  tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                  tickFormatter={(v) => {
                    const [, m] = String(v).split("-");
                    return new Date(0, parseInt(m, 10) - 1).toLocaleString(locale, { month: "short" });
                  }}
                />
                <YAxis tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} />
                <Tooltip
                  labelFormatter={(v) => {
                    const [y, m] = String(v).split("-");
                    return new Date(parseInt(y, 10), parseInt(m, 10) - 1).toLocaleString(locale, {
                      month: "long",
                      year: "numeric",
                    });
                  }}
                />
                <Bar dataKey="count" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} name={t("reports.newLeadsBar")} />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        <Card className="overflow-hidden border-border/80 bg-gradient-to-br from-card to-muted/15">
          <CardHeader className="pb-2">
            <CardTitle className="text-base font-semibold tracking-tight">{t("dashboard.chartDealsByStage")}</CardTitle>
            {dealsByStageList.length > 0 && (
              <p className="text-xs text-muted-foreground mt-1">
                {t("dashboard.chartDealsSummary", {
                  count: dealsStageSummary.count,
                  value: formatCurrency(dealsStageSummary.value),
                })}
              </p>
            )}
          </CardHeader>
          <CardContent className="pt-0">
            {dealsByStageList.length > 0 ? (
              <div className="rounded-xl bg-muted/25 dark:bg-muted/10 ring-1 ring-border/60 px-1 py-2">
                <ResponsiveContainer width="100%" height={268}>
                  <BarChart
                    data={dealsByStageList}
                    layout="vertical"
                    margin={{ top: 8, right: isRTL ? 8 : 16, left: isRTL ? 16 : 8, bottom: 8 }}
                    barCategoryGap={12}
                  >
                    <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" horizontal={false} />
                    <XAxis
                      type="number"
                      allowDecimals={false}
                      tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                      tickLine={false}
                    />
                    <YAxis
                      type="category"
                      dataKey="stage"
                      width={language === "ar" ? 100 : 92}
                      tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }}
                      tickLine={false}
                      axisLine={false}
                      tickFormatter={(v) => getLabel(DEAL_STAGE_LABELS, DEAL_STAGE_LABELS_AR, String(v), language)}
                    />
                    <Tooltip
                      cursor={{ fill: "hsl(var(--muted) / 0.12)" }}
                      content={({ active, payload }) => {
                        if (!active || !payload?.length) return null;
                        const row = payload[0].payload as { stage: string; count: number; value: number };
                        const label = getLabel(DEAL_STAGE_LABELS, DEAL_STAGE_LABELS_AR, row.stage, language);
                        return (
                          <div className="rounded-lg border border-border bg-popover px-3 py-2.5 shadow-lg text-sm min-w-[168px]">
                            <p className="font-semibold text-foreground mb-1">{label}</p>
                            <div className="flex justify-between gap-4 text-xs text-muted-foreground">
                              <span>{t("reports.count")}</span>
                              <span className="font-medium text-foreground tabular-nums">{row.count}</span>
                            </div>
                            <div className="flex justify-between gap-4 text-xs text-muted-foreground mt-0.5">
                              <span>{t("common.value")}</span>
                              <span className="font-medium text-foreground tabular-nums">{formatCurrency(Number(row.value))}</span>
                            </div>
                          </div>
                        );
                      }}
                    />
                    <Bar dataKey="count" name={t("reports.count")} radius={[0, 8, 8, 0]} animationDuration={600}>
                      {dealsByStageList.map((entry: { stage: string }) => (
                        <Cell key={entry.stage} fill={DEAL_STAGE_CHART_COLORS[entry.stage] ?? "#94a3b8"} />
                      ))}
                    </Bar>
                  </BarChart>
                </ResponsiveContainer>
              </div>
            ) : (
              <div className="h-[268px] flex items-center justify-center text-muted-foreground text-sm rounded-xl bg-muted/20">
                {t("dashboard.noDealsYet")}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Charts Row 2 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        <Card>
          <CardHeader>
            <CardTitle>{t("reports.funnel")}</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              {conversionFunnel.map((item, i) => {
                const maxVal = conversionFunnel[0].count || 1;
                const pct = Math.round((item.count / maxVal) * 100);
                return (
                  <div key={item.label}>
                    <div className="flex items-center justify-between mb-1">
                      <span className="text-sm font-medium text-foreground">{item.label}</span>
                      <span className="text-sm font-bold text-foreground">{item.count}</span>
                    </div>
                    <div className="h-8 bg-muted rounded-lg overflow-hidden">
                      <div
                        className="h-full rounded-lg flex items-center px-3 transition-all"
                        style={{
                          width: `${Math.max(pct, 5)}%`,
                          backgroundColor: COLORS[i % COLORS.length],
                        }}
                      >
                        <span className="text-white text-xs font-medium">{pct}%</span>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>{t("reports.leadsSource")}</CardTitle>
          </CardHeader>
          <CardContent>
            {leadSourceChartData.length > 0 ? (
              <ResponsiveContainer width="100%" height={240}>
                <PieChart>
                  <Pie
                    data={leadSourceChartData}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    innerRadius={55}
                    outerRadius={90}
                    paddingAngle={3}
                  >
                    {leadSourceChartData.map((_: unknown, i: number) => (
                      <Cell key={i} fill={COLORS[i % COLORS.length]} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(val: number, name: string, entry: { payload?: { pct?: number } }) => [`${val} (${entry?.payload?.pct ?? 0}%)`, name]} />
                  <Legend iconType="circle" iconSize={8} />
                </PieChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-[240px] flex items-center justify-center text-muted-foreground text-sm">
                {t("common.noData")}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Performance summary table */}
      <Card>
        <CardHeader>
          <CardTitle>{t("reports.kpi")}</CardTitle>
        </CardHeader>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  {t("reports.kpiMetric")}
                </th>
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  {t("reports.kpiValue")}
                </th>
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">
                  {t("reports.kpiStatus")}
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {[
                {
                  metric: t("reports.kpiConversion"),
                  value: `${stats.conversionRate ?? 0}%`,
                  status: (stats.conversionRate ?? 0) >= 20 ? "good" : "attention",
                },
                {
                  metric: t("reports.kpiNewLeadsMonth"),
                  value: stats.newLeadsThisMonth ?? 0,
                  status: "neutral",
                },
                {
                  metric: t("reports.kpiOpenTickets"),
                  value: stats.openTickets ?? 0,
                  status: (stats.openTickets ?? 0) > 10 ? "attention" : "good",
                },
                {
                  metric: t("reports.kpiPendingTasks"),
                  value: stats.pendingTasks ?? 0,
                  status: (stats.pendingTasks ?? 0) > 20 ? "attention" : "good",
                },
                {
                  metric: t("reports.kpiWonDeals"),
                  value: stats.wonDeals ?? 0,
                  status: "good",
                },
                {
                  metric: t("reports.kpiRevenueYtd"),
                  value: formatCurrency(stats.totalRevenue ?? 0),
                  status: "good",
                },
                {
                  metric: t("reports.kpiQuotes"),
                  value: stats.quotesTotal ?? 0,
                  status: "neutral",
                },
                {
                  metric: t("reports.kpiInvoices"),
                  value: stats.invoicesTotal ?? 0,
                  status: "neutral",
                },
              ].map((row, i) => (
                <tr key={i} className="hover:bg-muted/40">
                  <td className="px-6 py-3 font-medium text-foreground">{row.metric}</td>
                  <td className="px-6 py-3 font-bold text-foreground">{row.value}</td>
                  <td className="px-6 py-3">
                    <span
                      className={`inline-flex items-center gap-1.5 text-xs font-medium px-2 py-0.5 rounded-full ${
                        row.status === "good"
                          ? "bg-green-100 text-green-700"
                          : row.status === "attention"
                            ? "bg-amber-100 text-amber-700"
                            : "bg-gray-100 text-gray-600"
                      }`}
                    >
                      <div
                        className={`w-1.5 h-1.5 rounded-full ${
                          row.status === "good"
                            ? "bg-green-500"
                            : row.status === "attention"
                              ? "bg-amber-500"
                              : "bg-gray-400"
                        }`}
                      />
                      {row.status === "good"
                        ? t("reports.onTrack")
                        : row.status === "attention"
                          ? t("reports.needsAttention")
                          : t("reports.neutral")}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </AppShell>
  );
}
