"use client";
// src/app/dashboard/page.tsx
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { AppShell } from "@/components/layout/AppShell";
import { Card, CardHeader, CardTitle, CardContent, StatCard, LeadStatusBadge } from "@/components/ui/index";
import { useAuth } from "@/hooks/useAuth";
import { useLanguage } from "@/i18n/LanguageContext";
import { formatCurrency, formatRelativeTime, OPP_STAGE_LABELS, OPP_STAGE_LABELS_AR } from "@/lib/utils";
import { DEAL_STAGE_CHART_COLORS, dealStageGradientId } from "@/lib/chartColors";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell,
  Legend,
  Label,
} from "recharts";
import {
  TrendingUp,
  Users,
  DollarSign,
  Briefcase,
  Ticket,
  CheckSquare,
  ArrowRight,
  Loader2,
} from "lucide-react";


interface DashboardData {
  stats: {
    totalLeads: number;
    newLeadsThisMonth: number;
    totalContacts?: number;
    totalCustomers: number;
    totalDeals: number;
    totalOpportunities?: number;
    wonDeals: number;
    openTickets: number;
    pendingTasks: number;
    totalRevenue: number;
    conversionRate: number;
    quotesTotal?: number;
    invoicesTotal?: number;
  };
  recentLeads: Array<{
    id: string;
    firstName: string;
    lastName: string;
    company: string | null;
    status: string;
    source: string;
    createdAt: string;
    assignedTo: { name: string } | null;
  }>;
  dealsByStage: Array<{ stage: string; count: number; value: number }>;
  leadsLastSixMonths: Array<{ month: string; count: number }>;
}

export default function DashboardPage() {
  const { user } = useAuth();
  const { t, language, isRTL } = useLanguage();
  const stageLabels = language === "ar" ? OPP_STAGE_LABELS_AR : OPP_STAGE_LABELS;
  const [data, setData] = useState<DashboardData | null>(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 dealsPieData = useMemo(() => {
    if (!data?.dealsByStage?.length) return [];
    return data.dealsByStage.map((d) => ({
      ...d,
      name: stageLabels[d.stage] ?? d.stage,
    }));
  }, [data?.dealsByStage, stageLabels]);

  const dealsPieTotals = useMemo(() => {
    const count = dealsPieData.reduce((s, d) => s + d.count, 0);
    const value = dealsPieData.reduce((s, d) => s + d.value, 0);
    return { count, value };
  }, [dealsPieData]);

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

  const stats = data?.stats;

  const firstName = user?.name?.split(" ")[0] ?? "";
  const tod = getTimeOfDay();
  const greetingKey =
    tod === "morning"
      ? ("dashboard.greetingMorning" as const)
      : tod === "afternoon"
        ? ("dashboard.greetingAfternoon" as const)
        : ("dashboard.greetingEvening" as const);

  return (
    <AppShell breadcrumbs={[{ label: t("dashboard.title") }]}>
      {/* Welcome */}
      <div className="mb-6">
        <h1 className="text-xl font-bold text-foreground">
          {t(greetingKey, { name: firstName })}
        </h1>
        <p className="text-sm text-muted-foreground mt-0.5">
          {t("dashboard.whatsHappening")}
        </p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 sm: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" />}
          iconBg="bg-blue-100 dark:bg-blue-900/30"
        />
        <StatCard
          title={t("dashboard.cardTotalCustomers")}
          value={stats?.totalCustomers ?? 0}
          change={t("dashboard.conversionRateChange", { rate: stats?.conversionRate ?? 0 })}
          changeType="neutral"
          icon={<Users className="w-5 h-5" />}
          iconBg="bg-green-100 dark:bg-green-900/30"
        />
        <StatCard
          title={t("dashboard.cardTotalRevenue")}
          value={formatCurrency(stats?.totalRevenue ?? 0)}
          change={t("dashboard.revenueYearLabel")}
          changeType="up"
          icon={<DollarSign className="w-5 h-5" />}
          iconBg="bg-emerald-100 dark:bg-emerald-900/30"
        />
        <StatCard
          title={t("dashboard.cardActiveDeals")}
          value={stats?.totalDeals ?? 0}
          change={t("dashboard.closedWonCount", { count: stats?.wonDeals ?? 0 })}
          changeType="up"
          icon={<Briefcase className="w-5 h-5" />}
          iconBg="bg-purple-100 dark:bg-purple-900/30"
        />
      </div>

      {/* Secondary stats */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-6">
        <Card className="p-4 flex items-center gap-3 sm:gap-4">
          <div className="w-10 h-10 rounded-lg bg-amber-100 flex items-center justify-center">
            <CheckSquare className="w-5 h-5 text-amber-600" />
          </div>
          <div>
            <p className="text-2xl font-bold">{stats?.pendingTasks ?? 0}</p>
            <p className="text-xs text-muted-foreground">{t("dashboard.pendingTasksShort")}</p>
          </div>
          <Link href="/tasks" className="ms-auto text-muted-foreground hover:text-primary">
            <ArrowRight className={isRTL ? "w-4 h-4 rotate-180" : "w-4 h-4"} />
          </Link>
        </Card>
        <Card className="p-4 flex items-center gap-3 sm:gap-4">
          <div className="w-10 h-10 rounded-lg bg-red-100 flex items-center justify-center">
            <Ticket className="w-5 h-5 text-red-600" />
          </div>
          <div>
            <p className="text-2xl font-bold">{stats?.openTickets ?? 0}</p>
            <p className="text-xs text-muted-foreground">{t("dashboard.openTicketsShort")}</p>
          </div>
          <Link href="/tickets" className="ms-auto text-muted-foreground hover:text-primary">
            <ArrowRight className={isRTL ? "w-4 h-4 rotate-180" : "w-4 h-4"} />
          </Link>
        </Card>
      </div>

      {/* Charts row */}
      <div className="grid grid-cols-1 lg:grid-cols-5 gap-6 mb-6">
        {/* Deals by stage pie */}
        <Card className="lg:col-span-2 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>
            {dealsPieData.length > 0 && (
              <p className="text-xs text-muted-foreground mt-1">
                {t("dashboard.chartDealsSummary", {
                  count: dealsPieTotals.count,
                  value: formatCurrency(dealsPieTotals.value),
                })}
              </p>
            )}
          </CardHeader>
          <CardContent className="pt-0">
            {dealsPieData.length > 0 ? (
              <div className="relative rounded-xl bg-muted/25 dark:bg-muted/10 ring-1 ring-border/60 px-1 py-2">
                <ResponsiveContainer width="100%" height={288}>
                  <PieChart margin={{ top: 4, right: isRTL ? 4 : 8, left: isRTL ? 8 : 4, bottom: 4 }}>
                    <defs>
                      {dealsPieData.map((entry) => {
                        const c = DEAL_STAGE_CHART_COLORS[entry.stage] ?? "#94a3b8";
                        return (
                          <linearGradient key={entry.stage} id={dealStageGradientId(entry.stage)} x1="0" y1="0" x2="1" y2="1">
                            <stop offset="0%" stopColor={c} stopOpacity={1} />
                            <stop offset="100%" stopColor={c} stopOpacity={0.65} />
                          </linearGradient>
                        );
                      })}
                    </defs>
                    <Pie
                      data={dealsPieData}
                      dataKey="count"
                      nameKey="name"
                      cx="42%"
                      cy="50%"
                      innerRadius="58%"
                      outerRadius="88%"
                      paddingAngle={2.5}
                      stroke="hsl(var(--background))"
                      strokeWidth={2}
                      animationDuration={700}
                      labelLine={false}
                    >
                      {dealsPieData.map((entry) => (
                        <Cell
                          key={entry.stage}
                          fill={`url(#${dealStageGradientId(entry.stage)})`}
                        />
                      ))}
                      <Label
                        position="center"
                        content={({ viewBox }) => {
                          const cx = (viewBox as { cx?: number }).cx ?? 0;
                          const cy = (viewBox as { cy?: number }).cy ?? 0;
                          return (
                            <text textAnchor="middle" dominantBaseline="middle">
                              <tspan x={cx} y={cy - 10} className="fill-foreground text-2xl font-bold tracking-tight">
                                {dealsPieTotals.count}
                              </tspan>
                              <tspan x={cx} y={cy + 10} className="fill-muted-foreground text-[11px] font-medium">
                                {t("reports.count")}
                              </tspan>
                              <tspan x={cx} y={cy + 28} className="fill-foreground text-xs font-semibold opacity-90">
                                {formatCurrency(dealsPieTotals.value)}
                              </tspan>
                            </text>
                          );
                        }}
                      />
                    </Pie>
                    <Tooltip
                      cursor={{ fill: "hsl(var(--muted) / 0.15)" }}
                      content={({ active, payload }) => {
                        if (!active || !payload?.length) return null;
                        const p = payload[0].payload as (typeof dealsPieData)[0];
                        return (
                          <div className="rounded-lg border border-border bg-popover px-3 py-2.5 shadow-lg text-sm min-w-[160px]">
                            <p className="font-semibold text-foreground mb-1">{p.name}</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">{p.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(p.value)}</span>
                            </div>
                          </div>
                        );
                      }}
                    />
                    <Legend
                      verticalAlign="middle"
                      align={isRTL ? "left" : "right"}
                      layout="vertical"
                      iconType="circle"
                      iconSize={9}
                      wrapperStyle={{ fontSize: "11px", lineHeight: "1.45", paddingLeft: isRTL ? 0 : 4, paddingRight: isRTL ? 4 : 0 }}
                      formatter={(value) => <span className="text-muted-foreground">{value}</span>}
                    />
                  </PieChart>
                </ResponsiveContainer>
              </div>
            ) : (
              <div className="h-[288px] flex items-center justify-center text-muted-foreground text-sm rounded-xl bg-muted/20">
                {t("dashboard.noDealsYet")}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Leads trend bar chart */}
        <Card className="lg:col-span-3">
          <CardHeader>
            <CardTitle>{t("dashboard.chartLeadsSixMonths")}</CardTitle>
          </CardHeader>
          <CardContent>
            {data?.leadsLastSixMonths && data.leadsLastSixMonths.length > 0 ? (
              <ResponsiveContainer width="100%" height={220}>
                <BarChart data={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] = v.split("-");
                      return new Date(0, parseInt(m) - 1).toLocaleString("en", { month: "short" });
                    }}
                  />
                  <YAxis tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} />
                  <Tooltip
                    labelFormatter={(v) => {
                      const [y, m] = v.split("-");
                      return new Date(parseInt(y), parseInt(m) - 1).toLocaleString("en", { month: "long", year: "numeric" });
                    }}
                  />
                  <Bar dataKey="count" fill="hsl(var(--primary))" radius={[4, 4, 0, 0]} name={t("dashboard.chartSeriesLeads")} />
                </BarChart>
              </ResponsiveContainer>
            ) : (
              <div className="h-[220px] flex items-center justify-center text-muted-foreground text-sm">
                {t("dashboard.noDataYet")}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Recent Leads */}
      <Card>
        <CardHeader className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
          <CardTitle>{t("dashboard.recentLeads")}</CardTitle>
          <Link href="/leads" className="text-sm text-primary hover:underline flex items-center gap-1">
            {t("dashboard.viewAll")}{" "}
            <ArrowRight className={isRTL ? "w-3.5 h-3.5 rotate-180" : "w-3.5 h-3.5"} />
          </Link>
        </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("dashboard.tableLeadName")}</th>
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">{t("dashboard.tableCompany")}</th>
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">{t("dashboard.tableStatus")}</th>
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">{t("dashboard.tableAssigned")}</th>
                <th className="px-6 py-3 text-start text-xs font-semibold text-muted-foreground uppercase tracking-wider">{t("dashboard.tableCreated")}</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {data?.recentLeads?.length === 0 && (
                <tr>
                  <td colSpan={5} className="px-6 py-8 text-center text-muted-foreground">
                    {t("dashboard.noLeadsYet")}
                  </td>
                </tr>
              )}
              {data?.recentLeads?.map((lead) => (
                <tr key={lead.id} className="hover:bg-muted/40 transition-colors">
                  <td className="px-6 py-3">
                    <Link href={`/leads/${lead.id}`} className="font-medium text-primary hover:underline">
                      {lead.firstName} {lead.lastName}
                    </Link>
                  </td>
                  <td className="px-6 py-3 text-muted-foreground">{lead.company ?? "—"}</td>
                  <td className="px-6 py-3">
                    <LeadStatusBadge status={lead.status} />
                  </td>
                  <td className="px-6 py-3 text-muted-foreground">{lead.assignedTo?.name ?? "—"}</td>
                  <td className="px-6 py-3 text-muted-foreground text-xs">
                    {formatRelativeTime(lead.createdAt, language)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </AppShell>
  );
}

function getTimeOfDay() {
  const h = new Date().getHours();
  if (h < 12) return "morning";
  if (h < 18) return "afternoon";
  return "evening";
}
