"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Area, AreaChart, CartesianGrid, XAxis } from "recharts";
import { PlusIcon, TrendingDownIcon, TrendingUpIcon } from "lucide-react";
import { ErrorState } from "@/components/layout/ErrorState";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardAction,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  ChartConfig,
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
} from "@/components/ui/chart";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Skeleton } from "@/components/ui/skeleton";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { DataTable, type DataTableRow } from "@/components/dashboard/data-table";
import { apiFetch } from "@/lib/api";
import { formatRole } from "@/lib/roles";
import { formatSubscriptionStatus, subscriptionStatusBadgeVariant } from "@/lib/status";
import { useIsMobile } from "@/hooks/use-mobile";

type Vehicle = { id: string; name: string; isActive: boolean };
type Me = { user: { email: string; firstName?: string | null }; tenant: { name: string } | null };
type Sub = { status: string; plan: { name: string; code: string } };
type GeotabStatus = { connected: boolean; addinStatus: string };

const chartData = [
  { date: "2024-04-01", active: 8, inactive: 2 },
  { date: "2024-04-08", active: 10, inactive: 2 },
  { date: "2024-04-15", active: 12, inactive: 3 },
  { date: "2024-04-22", active: 14, inactive: 3 },
  { date: "2024-04-29", active: 15, inactive: 4 },
  { date: "2024-05-06", active: 18, inactive: 3 },
  { date: "2024-05-13", active: 20, inactive: 4 },
  { date: "2024-05-20", active: 22, inactive: 3 },
  { date: "2024-05-27", active: 24, inactive: 4 },
  { date: "2024-06-03", active: 26, inactive: 5 },
  { date: "2024-06-10", active: 28, inactive: 4 },
  { date: "2024-06-17", active: 30, inactive: 5 },
  { date: "2024-06-24", active: 32, inactive: 4 },
  { date: "2024-06-30", active: 34, inactive: 5 },
];

const chartConfig = {
  active: {
    label: "Active",
    color: "hsl(var(--chart-1))",
  },
  inactive: {
    label: "Inactive",
    color: "hsl(var(--chart-2))",
  },
} satisfies ChartConfig;

function SectionCards({
  vehicles,
  activeVehicles,
  sub,
  geotab,
  email,
}: {
  vehicles: Vehicle[];
  activeVehicles: number;
  sub: Sub | undefined;
  geotab: GeotabStatus | null;
  email: string;
}) {
  const inactive = vehicles.length - activeVehicles;
  return (
    <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4">
      <Card className="bg-gradient-to-t from-primary/5 to-card shadow-sm">
        <CardHeader>
          <CardDescription>Vehicles</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums sm:text-3xl">
            {vehicles.length}
          </CardTitle>
          <CardAction>
            <Badge variant="outline">
              <TrendingUpIcon />
              {activeVehicles} active
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            Fleet devices in tenant <TrendingUpIcon className="size-4" />
          </div>
          <div className="text-muted-foreground">{inactive} inactive</div>
        </CardFooter>
      </Card>
      <Card className="bg-gradient-to-t from-primary/5 to-card shadow-sm">
        <CardHeader>
          <CardDescription>Subscription</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums sm:text-3xl">
            {sub?.plan.name ?? "—"}
          </CardTitle>
          <CardAction>
            <Badge variant={sub ? subscriptionStatusBadgeVariant(sub.status) : "outline"}>
              {sub ? formatSubscriptionStatus(sub.status) : "None"}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            {sub ? "Plan entitlements active" : "No plan selected"}
          </div>
          <div className="text-muted-foreground">{sub?.plan.code ?? "Choose a subscription"}</div>
        </CardFooter>
      </Card>
      <Card className="bg-gradient-to-t from-primary/5 to-card shadow-sm">
        <CardHeader>
          <CardDescription>MyGeotab</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums sm:text-3xl">
            {geotab?.connected ? "Connected" : "Offline"}
          </CardTitle>
          <CardAction>
            <Badge variant="outline">
              {geotab?.connected ? <TrendingUpIcon /> : <TrendingDownIcon />}
              {geotab?.addinStatus ?? "unknown"}
            </Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            {geotab?.connected ? "Integration healthy" : "Needs attention"}
          </div>
          <div className="text-muted-foreground">Add-in link status</div>
        </CardFooter>
      </Card>
      <Card className="bg-gradient-to-t from-primary/5 to-card shadow-sm">
        <CardHeader>
          <CardDescription>Account</CardDescription>
          <CardTitle className="truncate text-xl font-semibold sm:text-2xl">{email || "—"}</CardTitle>
          <CardAction>
            <Badge variant="outline">Admin</Badge>
          </CardAction>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">{formatRole("CUSTOMER_ADMIN")}</div>
          <div className="text-muted-foreground">Signed-in workspace user</div>
        </CardFooter>
      </Card>
    </div>
  );
}

function ChartAreaInteractive() {
  const isMobile = useIsMobile();
  const [timeRange, setTimeRange] = useState("90d");

  useEffect(() => {
    if (isMobile) setTimeRange("30d");
  }, [isMobile]);

  const filteredData = useMemo(() => {
    const referenceDate = new Date("2024-06-30");
    let daysToSubtract = 90;
    if (timeRange === "30d") daysToSubtract = 30;
    if (timeRange === "7d") daysToSubtract = 7;
    const startDate = new Date(referenceDate);
    startDate.setDate(startDate.getDate() - daysToSubtract);
    return chartData.filter((item) => new Date(item.date) >= startDate);
  }, [timeRange]);

  return (
    <Card>
      <CardHeader className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <CardTitle>Fleet activity</CardTitle>
          <CardDescription>Active vs inactive vehicles</CardDescription>
        </div>
        <div className="flex items-center gap-2">
          <ToggleGroup
            type="single"
            value={timeRange}
            onValueChange={(value) => value && setTimeRange(value)}
            variant="outline"
            className="hidden md:flex"
          >
            <ToggleGroupItem value="90d">Last 3 months</ToggleGroupItem>
            <ToggleGroupItem value="30d">Last 30 days</ToggleGroupItem>
            <ToggleGroupItem value="7d">Last 7 days</ToggleGroupItem>
          </ToggleGroup>
          <Select value={timeRange} onValueChange={setTimeRange}>
            <SelectTrigger className="w-40 md:hidden" aria-label="Select a value">
              <SelectValue placeholder="Last 3 months" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="90d">Last 3 months</SelectItem>
              <SelectItem value="30d">Last 30 days</SelectItem>
              <SelectItem value="7d">Last 7 days</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </CardHeader>
      <CardContent className="px-2 pt-4 sm:px-6 sm:pt-6">
        <ChartContainer config={chartConfig} className="aspect-auto h-[250px] w-full">
          <AreaChart data={filteredData}>
            <defs>
              <linearGradient id="fillActive" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="var(--color-active)" stopOpacity={1} />
                <stop offset="95%" stopColor="var(--color-active)" stopOpacity={0.1} />
              </linearGradient>
              <linearGradient id="fillInactive" x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor="var(--color-inactive)" stopOpacity={0.8} />
                <stop offset="95%" stopColor="var(--color-inactive)" stopOpacity={0.1} />
              </linearGradient>
            </defs>
            <CartesianGrid vertical={false} />
            <XAxis
              dataKey="date"
              tickLine={false}
              axisLine={false}
              tickMargin={8}
              minTickGap={32}
              tickFormatter={(value) =>
                new Date(value).toLocaleDateString("en-US", { month: "short", day: "numeric" })
              }
            />
            <ChartTooltip
              cursor={false}
              content={
                <ChartTooltipContent
                  labelFormatter={(value) =>
                    new Date(value).toLocaleDateString("en-US", { month: "short", day: "numeric" })
                  }
                  indicator="dot"
                />
              }
            />
            <Area
              dataKey="inactive"
              type="natural"
              fill="url(#fillInactive)"
              stroke="var(--color-inactive)"
              stackId="a"
            />
            <Area
              dataKey="active"
              type="natural"
              fill="url(#fillActive)"
              stroke="var(--color-active)"
              stackId="a"
            />
          </AreaChart>
        </ChartContainer>
      </CardContent>
    </Card>
  );
}

export default function DashboardPage() {
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [me, setMe] = useState<Me | null>(null);
  const [subs, setSubs] = useState<Sub[]>([]);
  const [geotab, setGeotab] = useState<GeotabStatus | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    Promise.all([
      apiFetch<Vehicle[]>("/vehicles"),
      apiFetch<Me>("/auth/me"),
      apiFetch<Sub[]>("/subscriptions"),
      apiFetch<GeotabStatus>("/geotab/status"),
    ])
      .then(([v, profile, s, g]) => {
        setVehicles(v);
        setMe(profile);
        setSubs(s);
        setGeotab(g);
      })
      .catch((err) => setError(err instanceof Error ? err.message : "Failed to load"))
      .finally(() => setLoading(false));
  }, []);

  const activeVehicles = useMemo(() => vehicles.filter((v) => v.isActive).length, [vehicles]);
  const sub = subs[0];

  const tableRows: DataTableRow[] = useMemo(
    () =>
      vehicles.map((v, index) => ({
        id: v.id,
        header: v.name,
        type: "Vehicle",
        status: v.isActive ? "Done" : "In Process",
        target: String(index + 1),
        limit: v.isActive ? "10" : "5",
        reviewer: v.isActive ? "Eddie Lake" : "Assign reviewer",
        href: "/devices",
      })),
    [vehicles],
  );

  return (
    <div className="flex flex-1 flex-col gap-4 md:gap-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-lg font-semibold tracking-tight">Dashboard</h2>
          <p className="text-sm text-muted-foreground">
            {me?.tenant?.name
              ? `Welcome back${me.user.firstName ? `, ${me.user.firstName}` : ""} — ${me.tenant.name}`
              : "Overview of your fleet workspace"}
          </p>
        </div>
        <Button asChild size="sm">
          <Link href="/devices">
            <PlusIcon />
            Quick Create
          </Link>
        </Button>
      </div>

      {error ? <ErrorState message={error} /> : null}

      {loading ? (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
          {Array.from({ length: 4 }).map((_, i) => (
            <Skeleton key={i} className="h-36 rounded-xl" />
          ))}
        </div>
      ) : (
        <>
          <SectionCards
            vehicles={vehicles}
            activeVehicles={activeVehicles}
            sub={sub}
            geotab={geotab}
            email={me?.user.email ?? ""}
          />
          <ChartAreaInteractive />
          <DataTable
            data={tableRows}
            addHref="/devices"
            addLabel="Add Vehicle"
            tabs={[
              { value: "outline", label: "Outline" },
              { value: "past-performance", label: "Past Performance", badge: 3 },
              { value: "key-personnel", label: "Key Personnel", badge: 2 },
              { value: "focus-documents", label: "Focus Documents" },
            ]}
          />
        </>
      )}
    </div>
  );
}
