"use client";

import { useState } from "react";
import {
  Building2,
  Users,
  Car,
  CreditCard,
  MapPin,
  Activity,
} from "lucide-react";
import {
  Area,
  AreaChart,
  Bar,
  BarChart,
  CartesianGrid,
  Cell,
  Pie,
  PieChart,
  XAxis,
  YAxis,
} from "recharts";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT } from "@/shared/i18n/client";
import type { DashboardPeriod } from "@/domain/entities/dashboard-stats";
import StatsCard from "@/presentation/components/shared/stats-card";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/presentation/components/ui/card";
import { SearchableSelect } from "@/presentation/components/ui/searchable-select";
import {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
  type ChartConfig,
} from "@/presentation/components/ui/chart";

const PIE_COLORS = [
  "hsl(221, 83%, 53%)",
  "hsl(262, 83%, 58%)",
  "hsl(186, 77%, 45%)",
  "hsl(142, 71%, 45%)",
  "hsl(45, 93%, 47%)",
  "hsl(0, 84%, 60%)",
];

export default function DashboardPage() {
  const t = useT();
  usePageHeader(t.pages.dashboard.title, t.pages.dashboard.subtitle);
  const container = useRepositories();
  const [period, setPeriod] = useState<DashboardPeriod>("12m");

  const PERIOD_OPTIONS: { value: DashboardPeriod; label: string }[] = [
    { value: "7d", label: t.dashboard.periods["7d"] },
    { value: "30d", label: t.dashboard.periods["30d"] },
    { value: "90d", label: t.dashboard.periods["90d"] },
    { value: "12m", label: t.dashboard.periods["12m"] },
  ];

  const companyGrowthConfig: ChartConfig = {
    verified: { label: t.dashboard.charts.verified, color: "hsl(221, 83%, 53%)" },
    new: { label: t.dashboard.charts.newF, color: "hsl(142, 71%, 45%)" },
  };

  const vehicleGrowthConfig: ChartConfig = {
    connected: { label: t.dashboard.charts.connected, color: "hsl(186, 77%, 45%)" },
    new: { label: t.dashboard.charts.newM, color: "hsl(262, 83%, 58%)" },
  };

  const subscriptionConfig: ChartConfig = {
    active: { label: t.dashboard.charts.active, color: "hsl(142, 71%, 45%)" },
    trial: { label: t.dashboard.charts.trial, color: "hsl(45, 93%, 47%)" },
    expired: { label: t.dashboard.charts.expired, color: "hsl(0, 84%, 60%)" },
  };

  const { data: stats, loading } = useApiQuery(
    () => container.dashboardRepository.getStats(period),
    { deps: [period] }
  );

  return (
    <div className="p-6 space-y-6">
      <div className="flex items-center justify-end">
        <SearchableSelect
          triggerClassName="w-[140px]"
          value={period}
          onValueChange={(v) => setPeriod(v as DashboardPeriod)}
          options={PERIOD_OPTIONS.map((opt) => ({ value: opt.value, label: opt.label }))}
        />
      </div>

      {loading ? (
        <div className="space-y-6">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {Array.from({ length: 6 }).map((_, i) => (
              <Skeleton key={i} className="h-32 rounded-xl" />
            ))}
          </div>
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {Array.from({ length: 4 }).map((_, i) => (
              <Skeleton key={i} className="h-72 rounded-xl" />
            ))}
          </div>
        </div>
      ) : stats ? (
        <div className="space-y-6">
          {/* Stats cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            <StatsCard
              title={t.dashboard.stats.companies}
              value={stats.companies.total}
              subtitle={`${t.dashboard.stats.withVehicles(stats.companies.with_vehicles)}, ${t.dashboard.stats.newCompanies(stats.companies.new_last_30_days)}`}
              accent="blue"
              icon={Building2}
            />
            <StatsCard
              title={t.dashboard.stats.users}
              value={stats.users.total}
              accent="purple"
              icon={Users}
            />
            <StatsCard
              title={t.dashboard.stats.vehicles}
              value={stats.vehicles.total}
              subtitle={t.dashboard.stats.connected(stats.vehicles.connected)}
              accent="cyan"
              icon={Car}
            />
            <StatsCard
              title={t.dashboard.stats.subscriptions}
              value={stats.subscriptions.active}
              subtitle={t.dashboard.stats.onTrial(stats.subscriptions.trial)}
              accent="green"
              icon={CreditCard}
            />
            <StatsCard
              title={t.dashboard.stats.sites}
              value={stats.sites.total}
              accent="amber"
              icon={MapPin}
            />
            <StatsCard
              title={t.dashboard.stats.planDistribution}
              value={stats.plan_distribution.length + t.dashboard.stats.plansSuffix}
              subtitle={stats.plan_distribution
                .map((p) => `${p.plan}: ${p.count}`)
                .join(", ")}
              accent="red"
              icon={Activity}
            />
          </div>

          {/* Charts */}
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
            {/* Company Growth */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">{t.dashboard.charts.companyGrowth}</CardTitle>
                <CardDescription>{t.dashboard.charts.companyGrowthDesc}</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer
                  config={companyGrowthConfig}
                  className="h-[250px] w-full"
                >
                  <AreaChart data={stats.charts.company_growth}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} />
                    <XAxis dataKey="date" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} width={40} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Area
                      type="monotone"
                      dataKey="verified"
                      stackId="1"
                      fill="var(--color-verified)"
                      stroke="var(--color-verified)"
                      fillOpacity={0.4}
                    />
                    <Area
                      type="monotone"
                      dataKey="new"
                      stackId="1"
                      fill="var(--color-new)"
                      stroke="var(--color-new)"
                      fillOpacity={0.4}
                    />
                  </AreaChart>
                </ChartContainer>
              </CardContent>
            </Card>

            {/* Vehicle Growth */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">{t.dashboard.charts.vehicleGrowth}</CardTitle>
                <CardDescription>{t.dashboard.charts.vehicleGrowthDesc}</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer
                  config={vehicleGrowthConfig}
                  className="h-[250px] w-full"
                >
                  <AreaChart data={stats.charts.vehicle_growth}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} />
                    <XAxis dataKey="date" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} width={40} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Area
                      type="monotone"
                      dataKey="connected"
                      fill="var(--color-connected)"
                      stroke="var(--color-connected)"
                      fillOpacity={0.4}
                    />
                    <Area
                      type="monotone"
                      dataKey="new"
                      fill="var(--color-new)"
                      stroke="var(--color-new)"
                      fillOpacity={0.4}
                    />
                  </AreaChart>
                </ChartContainer>
              </CardContent>
            </Card>

            {/* Subscription Timeline */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">{t.dashboard.charts.subscriptionTimeline}</CardTitle>
                <CardDescription>{t.dashboard.charts.subscriptionTimelineDesc}</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer
                  config={subscriptionConfig}
                  className="h-[250px] w-full"
                >
                  <BarChart data={stats.charts.subscription_timeline}>
                    <CartesianGrid strokeDasharray="3 3" vertical={false} />
                    <XAxis dataKey="date" tickLine={false} axisLine={false} />
                    <YAxis tickLine={false} axisLine={false} width={40} />
                    <ChartTooltip content={<ChartTooltipContent />} />
                    <ChartLegend content={<ChartLegendContent />} />
                    <Bar
                      dataKey="active"
                      stackId="a"
                      fill="var(--color-active)"
                      radius={[0, 0, 0, 0]}
                    />
                    <Bar
                      dataKey="trial"
                      stackId="a"
                      fill="var(--color-trial)"
                      radius={[0, 0, 0, 0]}
                    />
                    <Bar
                      dataKey="expired"
                      stackId="a"
                      fill="var(--color-expired)"
                      radius={[4, 4, 0, 0]}
                    />
                  </BarChart>
                </ChartContainer>
              </CardContent>
            </Card>

            {/* Plan Distribution - Pie */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">{t.dashboard.charts.planDistribution}</CardTitle>
                <CardDescription>{t.dashboard.charts.planDistributionDesc}</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer
                  config={Object.fromEntries(
                    stats.charts.plan_distribution.map((item, i) => [
                      item.label,
                      {
                        label: item.label,
                        color: PIE_COLORS[i % PIE_COLORS.length],
                      },
                    ])
                  )}
                  className="h-[250px] w-full"
                >
                  <PieChart>
                    <ChartTooltip content={<ChartTooltipContent nameKey="label" />} />
                    <ChartLegend content={<ChartLegendContent nameKey="label" />} />
                    <Pie
                      data={stats.charts.plan_distribution}
                      dataKey="value"
                      nameKey="label"
                      cx="50%"
                      cy="50%"
                      innerRadius={50}
                      outerRadius={80}
                    >
                      {stats.charts.plan_distribution.map((_, i) => (
                        <Cell
                          key={i}
                          fill={PIE_COLORS[i % PIE_COLORS.length]}
                        />
                      ))}
                    </Pie>
                  </PieChart>
                </ChartContainer>
              </CardContent>
            </Card>

            {/* Motor Type Distribution - Pie */}
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">{t.dashboard.charts.motorTypes}</CardTitle>
                <CardDescription>{t.dashboard.charts.motorTypesDesc}</CardDescription>
              </CardHeader>
              <CardContent>
                <ChartContainer
                  config={Object.fromEntries(
                    stats.charts.motor_type_distribution.map((item, i) => [
                      item.label,
                      {
                        label: item.label,
                        color: PIE_COLORS[i % PIE_COLORS.length],
                      },
                    ])
                  )}
                  className="h-[250px] w-full"
                >
                  <PieChart>
                    <ChartTooltip content={<ChartTooltipContent nameKey="label" />} />
                    <ChartLegend content={<ChartLegendContent nameKey="label" />} />
                    <Pie
                      data={stats.charts.motor_type_distribution}
                      dataKey="value"
                      nameKey="label"
                      cx="50%"
                      cy="50%"
                      innerRadius={50}
                      outerRadius={80}
                    >
                      {stats.charts.motor_type_distribution.map((_, i) => (
                        <Cell
                          key={i}
                          fill={PIE_COLORS[i % PIE_COLORS.length]}
                        />
                      ))}
                    </Pie>
                  </PieChart>
                </ChartContainer>
              </CardContent>
            </Card>
          </div>
        </div>
      ) : (
        <div className="flex items-center justify-center h-64 rounded-xl border border-dashed border-border">
          <p className="text-muted-foreground text-sm">{t.dashboard.loadError}</p>
        </div>
      )}
    </div>
  );
}
