"use client";

import { useTranslations } from "next-intl";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Legend,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
  type LegendProps,
} from "recharts";
import { chartColor } from "@/lib/reports/analytics";
import { formatCurrency, formatNumber } from "@/lib/format";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import type { ReportsChartsProps } from "@/components/reports/reports-charts.types";

export type { ReportsChartPoint, ReportsPieSlice, ReportsChartsProps } from "@/components/reports/reports-charts.types";

export function ReportsCharts({
  isLoading,
  numberLocale,
  chartData,
  pieData,
  branchCompareData,
  showBranchCompare,
  branches,
}: ReportsChartsProps) {
  const t = useTranslations("reports");

  return (
    <>
      <div className="grid gap-4 lg:grid-cols-3">
        <Card className="rounded-xl border border-border/80 bg-card lg:col-span-2">
          <CardHeader>
            <CardTitle className="text-base">{t("revenueChartTitle")}</CardTitle>
          </CardHeader>
          <CardContent className="h-72">
            {isLoading ? (
              <ChartAreaSkeleton />
            ) : chartData.length === 0 ? (
              <p className="text-sm text-muted-foreground">{t("noData")}</p>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={chartData}>
                  <defs>
                    <linearGradient id="revFill" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#0F6E56" stopOpacity={0.35} />
                      <stop offset="95%" stopColor="#0F6E56" stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#e5e5e5" />
                  <XAxis dataKey="label" tick={{ fontSize: 11 }} interval="preserveStartEnd" />
                  <YAxis
                    tick={{ fontSize: 11 }}
                    tickFormatter={(v) => formatNumber(Number(v), numberLocale)}
                    width={56}
                  />
                  <Tooltip
                    formatter={(value: number) => formatCurrency(value, numberLocale)}
                    labelFormatter={(_, payload) =>
                      payload?.[0]?.payload?.date
                        ? String(payload[0].payload.date)
                        : ""
                    }
                  />
                  <Area
                    type="monotone"
                    dataKey="revenue"
                    name={t("revenue")}
                    stroke="#0F6E56"
                    fill="url(#revFill)"
                    strokeWidth={2}
                  />
                </AreaChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        <Card className="rounded-xl border border-border/80 bg-card">
          <CardHeader>
            <CardTitle className="text-base">{t("paymentMixTitle")}</CardTitle>
          </CardHeader>
          <CardContent className="h-72">
            {isLoading ? (
              <ChartPieSkeleton />
            ) : pieData.length === 0 ? (
              <p className="text-sm text-muted-foreground">{t("noData")}</p>
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={pieData}
                    dataKey="value"
                    nameKey="name"
                    cx="50%"
                    cy="50%"
                    innerRadius={48}
                    outerRadius={80}
                    paddingAngle={2}
                  >
                    {pieData.map((entry) => (
                      <Cell key={entry.key} fill={entry.fill} />
                    ))}
                  </Pie>
                  <Tooltip formatter={(value: number) => formatCurrency(value, numberLocale)} />
                  <Legend content={<ChartLegend />} />
                </PieChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>
      </div>

      {showBranchCompare ? (
        <Card className="rounded-xl border border-border/80 bg-card">
          <CardHeader>
            <CardTitle className="text-base">{t("branchCompareTitle")}</CardTitle>
          </CardHeader>
          <CardContent className="h-80">
            {isLoading ? (
              <ChartBarSkeleton />
            ) : (
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={branchCompareData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="label" tick={{ fontSize: 10 }} interval="preserveStartEnd" />
                  <YAxis
                    tickFormatter={(v) => formatNumber(Number(v), numberLocale)}
                    width={56}
                  />
                  <Tooltip formatter={(value: number) => formatCurrency(value, numberLocale)} />
                  <Legend content={<ChartLegend />} />
                  {branches.map((b, i) => (
                    <Bar
                      key={b.id}
                      dataKey={b.id}
                      name={b.name}
                      fill={chartColor(i)}
                      radius={[4, 4, 0, 0]}
                    />
                  ))}
                </BarChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>
      ) : null}
    </>
  );
}

function ChartLegend({ payload }: LegendProps) {
  if (!payload?.length) return null;
  return (
    <ul className="flex flex-wrap items-center justify-center gap-x-5 gap-y-2 pt-3">
      {payload.map((entry, index) => (
        <li
          key={`legend-${String(entry.value)}-${index}`}
          className="flex items-center gap-2 text-xs text-foreground"
        >
          <span
            className="inline-block size-2.5 shrink-0 rounded-sm"
            style={{ backgroundColor: entry.color }}
            aria-hidden
          />
          <span className="leading-none">{entry.value}</span>
        </li>
      ))}
    </ul>
  );
}

function ChartAreaSkeleton() {
  return (
    <div className="flex h-full flex-col justify-end gap-2 pt-4">
      <div className="flex h-full items-end gap-1">
        {[40, 65, 50, 80, 55, 70, 45].map((h, i) => (
          <Skeleton key={i} className="flex-1 rounded-t-md" style={{ height: `${h}%` }} />
        ))}
      </div>
      <Skeleton className="h-3 w-full" />
    </div>
  );
}

function ChartPieSkeleton() {
  return (
    <div className="flex h-full items-center justify-center">
      <Skeleton className="h-40 w-40 rounded-full" />
    </div>
  );
}

function ChartBarSkeleton() {
  return (
    <div className="flex h-full items-end gap-2 pt-4">
      {[55, 70, 45, 80, 60].map((h, i) => (
        <Skeleton key={i} className="flex-1 rounded-t-md" style={{ height: `${h}%` }} />
      ))}
    </div>
  );
}
