"use client";

import { format, parseISO } from "date-fns";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Area, CartesianGrid, ComposedChart, Line, XAxis } from "recharts";

import { Button } from "@/components/ui/button";
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import {
  type ChartConfig,
  ChartContainer,
  ChartLegend,
  ChartLegendContent,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectLabel,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

import {
  ADMIN_DASHBOARD_RANGES,
  type AdminDashboardRange,
  type AdminDashboardSeriesPoint,
} from "../_lib/admin-dashboard-types";

const chartConfig = {
  newCustomers: {
    label: "New Customers",
    color: "var(--chart-1)",
  },
  activeCustomers: {
    label: "Active Customers",
    color: "var(--chart-2)",
  },
  orders: {
    label: "Orders",
    color: "var(--chart-3)",
  },
} satisfies ChartConfig;

type PerformanceOverviewProps = {
  series: AdminDashboardSeriesPoint[];
  range: AdminDashboardRange;
};

export function PerformanceOverview({ series, range }: PerformanceOverviewProps) {
  const router = useRouter();
  const rangeMeta = ADMIN_DASHBOARD_RANGES.find((item) => item.value === range);

  return (
    <Card className="@container/card">
      <CardHeader>
        <CardTitle className="leading-none">Customer Activity</CardTitle>
        <CardDescription>
          <span className="@[540px]/card:block hidden">
            New customers, actives, and orders · {rangeMeta?.label ?? range}
          </span>
          <span className="@[540px]/card:hidden">{rangeMeta?.shortLabel ?? range}</span>
        </CardDescription>
        <CardAction className="flex items-center gap-2">
          <Select
            value={range}
            onValueChange={(value) => {
              router.push(`/dashboard?range=${value}`);
            }}
          >
            <SelectTrigger size="sm" className="w-36">
              <SelectValue placeholder="Period" />
            </SelectTrigger>
            <SelectContent>
              <SelectGroup>
                <SelectLabel>Period</SelectLabel>
                {ADMIN_DASHBOARD_RANGES.map((item) => (
                  <SelectItem key={item.value} value={item.value}>
                    {item.label}
                  </SelectItem>
                ))}
              </SelectGroup>
            </SelectContent>
          </Select>

          <Button variant="outline" size="sm" asChild>
            <Link href="/dashboard/customers">View customers</Link>
          </Button>
        </CardAction>
      </CardHeader>

      <CardContent>
        {series.length === 0 ? (
          <div className="flex h-80 items-center justify-center text-muted-foreground text-sm">
            No activity series for this period.
          </div>
        ) : (
          <ChartContainer config={chartConfig} className="aspect-auto h-80 w-full">
            <ComposedChart data={series} margin={{ top: 0 }}>
              <defs>
                <linearGradient id="fillNewCustomers" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="var(--color-newCustomers)" stopOpacity={0.36} />
                  <stop offset="95%" stopColor="var(--color-newCustomers)" stopOpacity={0.04} />
                </linearGradient>
              </defs>
              <CartesianGrid vertical={false} strokeOpacity={0.5} />

              <XAxis
                dataKey="date"
                tickLine={false}
                axisLine={false}
                tickMargin={8}
                minTickGap={48}
                tickFormatter={(value) => {
                  try {
                    return parseISO(value).toLocaleDateString("en-US", {
                      month: "short",
                      day: range === "12m" ? undefined : "numeric",
                      year: range === "12m" ? "2-digit" : undefined,
                    });
                  } catch {
                    return value;
                  }
                }}
              />

              <ChartTooltip
                cursor={false}
                content={
                  <ChartTooltipContent
                    className="w-50"
                    indicator="line"
                    labelFormatter={(value) => {
                      try {
                        return format(parseISO(String(value)), range === "12m" ? "MMMM yyyy" : "d MMMM yyyy");
                      } catch {
                        return String(value);
                      }
                    }}
                  />
                }
              />
              <ChartLegend verticalAlign="top" content={<ChartLegendContent className="mb-5 justify-end" />} />

              <Area
                dataKey="newCustomers"
                type="monotone"
                fill="url(#fillNewCustomers)"
                stroke="var(--color-newCustomers)"
                strokeWidth={1.25}
                dot={false}
                fillOpacity={1}
              />
              <Line
                dataKey="activeCustomers"
                type="monotone"
                stroke="var(--color-activeCustomers)"
                strokeWidth={1.4}
                dot={false}
              />
              <Line dataKey="orders" type="monotone" stroke="var(--color-orders)" strokeWidth={1.2} dot={false} />
            </ComposedChart>
          </ChartContainer>
        )}
      </CardContent>
    </Card>
  );
}
