"use client";

import { useMemo, useState } from "react";
import {
  ClipboardList,
  CheckCircle2,
  AlertTriangle,
  Hourglass,
  Timer,
  Search,
  Filter,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
  Cpu,
  Calendar,
  Clock,
  Camera,
  Loader2,
} from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { useServerPagination } from "@/presentation/hooks/use-server-pagination";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useT, useLocale } from "@/shared/i18n/client";
import { formatDate } from "@/shared/lib/format-date";
import StatsCard from "@/presentation/components/shared/stats-card";
import { StatusPill } from "@/presentation/components/telematics/status-pill";
import { Badge } from "@/presentation/components/ui/badge";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/presentation/components/ui/collapsible";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/presentation/components/ui/select";
import { InstallationDetailModal } from "@/presentation/components/installations/installation-detail-modal";
import type { Installation } from "@/domain/entities/installation";
import type { Locale } from "@/shared/i18n/config";

const STATUS_FILTER_VALUES = ["in_progress", "validated", "gps_error", "pending"];

function dayKey(installation: Installation): string {
  return (installation.intervention_date ?? installation.created_at).slice(0, 10);
}

function dayLabel(key: string, locale: Locale): string {
  return new Date(`${key}T00:00:00`)
    .toLocaleDateString(locale === "fr" ? "fr-FR" : "en-US", {
      weekday: "long",
      day: "numeric",
      month: "long",
      year: "numeric",
    })
    .toUpperCase();
}

function startTime(installation: Installation, locale: Locale): string {
  return new Date(installation.created_at).toLocaleTimeString(
    locale === "fr" ? "fr-FR" : "en-US",
    { hour: "2-digit", minute: "2-digit" }
  );
}

function InstallationCard({
  installation,
  locale,
  onClick,
}: {
  installation: Installation;
  locale: Locale;
  onClick: () => void;
}) {
  const t = useT();
  const plate = installation.vehicle.license_plate || t.installations.card.noPlate;
  const deviceLabel =
    installation.device.model ||
    installation.device.product_line ||
    t.installations.card.deviceUnknown;
  const imei = installation.device.imei;
  const date = installation.intervention_date ?? installation.created_at;

  return (
    <button
      type="button"
      onClick={onClick}
      className="w-full text-left bg-card rounded-xl border border-border border-l-4 shadow-sm hover:shadow-md transition-shadow p-4"
      style={{ borderLeftColor: installation.status_color }}
    >
      <div className="flex items-start justify-between gap-3">
        <div className="min-w-0 flex items-baseline gap-2 flex-wrap">
          <span className="text-base font-bold text-foreground font-mono truncate">
            {plate}
          </span>
          {installation.vehicle.fleet_vehicle_id && (
            <span className="text-xs text-muted-foreground">
              {t.installations.card.fleetVehicle(installation.vehicle.fleet_vehicle_id)}
            </span>
          )}
        </div>
        <div className="flex items-center gap-1.5 shrink-0">
          <StatusPill
            label={installation.status_label}
            color={installation.status_color}
          />
          <ChevronRight className="w-4 h-4 text-muted-foreground" />
        </div>
      </div>

      <div className="mt-2 flex items-center gap-2 text-sm">
        <Cpu className="w-4 h-4 text-primary shrink-0" />
        <span className="font-medium text-primary">{deviceLabel}</span>
        {imei && (
          <span className="font-mono text-xs text-muted-foreground truncate">
            — …{imei.slice(-6)}
          </span>
        )}
      </div>

      <div className="mt-2 flex items-center gap-4 text-xs text-muted-foreground">
        <span className="flex items-center gap-1.5">
          <Calendar className="w-3.5 h-3.5 shrink-0" />
          {formatDate(date, locale)}
        </span>
        <span className="flex items-center gap-1.5">
          <Clock className="w-3.5 h-3.5 shrink-0" />
          {startTime(installation, locale)}
          {installation.duration_minutes !== null &&
            ` · ${t.installations.card.minutes(installation.duration_minutes)}`}
        </span>
        <span className="flex items-center gap-1.5">
          <Camera className="w-3.5 h-3.5 shrink-0" />
          {t.installations.card.photos(installation.photos_count)}
        </span>
      </div>
    </button>
  );
}

export function InstallationsHistory() {
  const t = useT();
  const locale = useLocale();
  const container = useRepositories();
  const pagination = useServerPagination();

  const [filtersOpen, setFiltersOpen] = useState(false);
  const [detailId, setDetailId] = useState<number | null>(null);

  const { data: stats, refetch: refetchStats } = useApiQuery(
    () => container.installationRepository.getStats(),
    { deps: [] }
  );

  const { data: installers } = useApiQuery(
    () => container.installationRepository.getInstallerOptions(),
    { deps: [] }
  );

  const { data: response, loading, refetch: refetchList } = useApiQuery(
    () => container.installationRepository.findAll(pagination.params),
    { deps: [pagination.params] }
  );

  usePageHeader(
    t.pages.installations.title,
    t.pages.installations.subtitle(stats?.total ?? 0)
  );

  const items = useMemo(() => response?.items ?? [], [response]);
  const totalPages = response?.last_page ?? 1;

  const groups = useMemo(() => {
    const map = new Map<string, Installation[]>();
    for (const installation of items) {
      const key = dayKey(installation);
      map.set(key, [...(map.get(key) ?? []), installation]);
    }
    return [...map.entries()];
  }, [items]);

  const hasActiveFilters =
    Object.values(pagination.filters).some((v) => v !== undefined && v !== "");

  const resetFilters = () => {
    pagination.setFilter("status", undefined);
    pagination.setFilter("user_id", undefined);
    pagination.setFilter("date_from", undefined);
    pagination.setFilter("date_to", undefined);
  };

  return (
    <div className="space-y-4">
      {/* Search + results count */}
      <div className="flex items-center gap-3">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            value={pagination.search}
            onChange={(e) => pagination.setSearch(e.target.value)}
            placeholder={t.installations.searchPlaceholder}
            className="pl-9"
          />
        </div>
        <Badge variant="secondary" className="shrink-0">
          {t.installations.results(response?.total ?? 0)}
        </Badge>
      </div>

      {/* Filters */}
      <Collapsible open={filtersOpen} onOpenChange={setFiltersOpen}>
        <CollapsibleTrigger asChild>
          <Button variant="outline" size="sm">
            <Filter className="w-4 h-4 mr-2" />
            {t.installations.filters.title}
            <ChevronDown
              className={`w-4 h-4 ml-2 transition-transform ${filtersOpen ? "rotate-180" : ""}`}
            />
          </Button>
        </CollapsibleTrigger>
        <CollapsibleContent>
          <div className="mt-3 p-4 bg-card border border-border rounded-xl flex flex-wrap items-end gap-4">
            <div className="flex flex-col gap-1">
              <span className="text-[11px] font-medium text-muted-foreground leading-none">
                {t.installations.filters.status}
              </span>
              <Select
                value={(pagination.filters.status as string) ?? "all"}
                onValueChange={(v) =>
                  pagination.setFilter("status", v === "all" ? undefined : v)
                }
              >
                <SelectTrigger className="h-8 w-44 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">
                    {t.installations.filters.allStatuses}
                  </SelectItem>
                  {STATUS_FILTER_VALUES.map((s) => (
                    <SelectItem key={s} value={s}>
                      {t.installations.statusLabels[s] ?? s}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-col gap-1">
              <span className="text-[11px] font-medium text-muted-foreground leading-none">
                {t.installations.filters.installer}
              </span>
              <Select
                value={
                  pagination.filters.user_id !== undefined
                    ? String(pagination.filters.user_id)
                    : "all"
                }
                onValueChange={(v) =>
                  pagination.setFilter("user_id", v === "all" ? undefined : Number(v))
                }
              >
                <SelectTrigger className="h-8 w-48 text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">
                    {t.installations.filters.allInstallers}
                  </SelectItem>
                  {(installers ?? []).map((installer) => (
                    <SelectItem key={installer.id} value={String(installer.id)}>
                      {installer.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="flex flex-col gap-1">
              <span className="text-[11px] font-medium text-muted-foreground leading-none">
                {t.installations.filters.dateFrom}
              </span>
              <Input
                type="date"
                className="h-8 w-40 text-xs"
                value={(pagination.filters.date_from as string) ?? ""}
                onChange={(e) =>
                  pagination.setFilter("date_from", e.target.value || undefined)
                }
              />
            </div>
            <div className="flex flex-col gap-1">
              <span className="text-[11px] font-medium text-muted-foreground leading-none">
                {t.installations.filters.dateTo}
              </span>
              <Input
                type="date"
                className="h-8 w-40 text-xs"
                value={(pagination.filters.date_to as string) ?? ""}
                onChange={(e) =>
                  pagination.setFilter("date_to", e.target.value || undefined)
                }
              />
            </div>
            {hasActiveFilters && (
              <Button variant="ghost" size="sm" onClick={resetFilters}>
                {t.installations.filters.reset}
              </Button>
            )}
          </div>
        </CollapsibleContent>
      </Collapsible>

      {/* Stats */}
      {stats && (
        <div className="grid grid-cols-2 lg:grid-cols-5 gap-4">
          <StatsCard
            title={t.installations.stats.total}
            value={stats.total}
            icon={ClipboardList}
            accent="blue"
          />
          <StatsCard
            title={t.installations.stats.validated}
            value={stats.validees}
            icon={CheckCircle2}
            accent="green"
          />
          <StatsCard
            title={t.installations.stats.pending}
            value={stats.en_attente ?? 0}
            icon={Hourglass}
            accent="amber"
          />
          <StatsCard
            title={t.installations.stats.toFix}
            value={stats.a_corriger}
            icon={AlertTriangle}
            accent="red"
          />
          <StatsCard
            title={t.installations.stats.avgMin}
            value={stats.avg_minutes ?? "—"}
            icon={Timer}
            accent="cyan"
          />
        </div>
      )}

      {/* Grouped list */}
      {loading ? (
        <div className="flex items-center justify-center py-16">
          <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
        </div>
      ) : items.length === 0 ? (
        <div className="flex flex-col items-center justify-center text-center py-16 px-6 bg-card border border-border rounded-xl">
          <div className="w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4">
            <ClipboardList className="w-8 h-8 text-primary" />
          </div>
          <p className="text-base font-semibold text-foreground">
            {t.installations.empty}
          </p>
          <p className="text-sm text-muted-foreground mt-1 max-w-xs">
            {t.installations.emptyHint}
          </p>
        </div>
      ) : (
        <div className="space-y-6">
          {groups.map(([key, group]) => (
            <div key={key} className="space-y-3">
              <div className="flex items-center gap-2">
                <span className="text-xs font-semibold tracking-wide text-foreground">
                  {dayLabel(key, locale)}
                </span>
                <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                  {group.length}
                </Badge>
              </div>
              {group.map((installation) => (
                <InstallationCard
                  key={installation.id}
                  installation={installation}
                  locale={locale}
                  onClick={() => setDetailId(installation.id)}
                />
              ))}
            </div>
          ))}
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-end gap-2">
          <Button
            variant="outline"
            size="icon-sm"
            onClick={() => pagination.setPage(Math.max(1, pagination.page - 1))}
            disabled={pagination.page === 1}
          >
            <ChevronLeft className="w-4 h-4" />
          </Button>
          <span className="text-xs text-muted-foreground">
            {pagination.page} / {totalPages}
          </span>
          <Button
            variant="outline"
            size="icon-sm"
            onClick={() =>
              pagination.setPage(Math.min(totalPages, pagination.page + 1))
            }
            disabled={pagination.page === totalPages}
          >
            <ChevronRight className="w-4 h-4" />
          </Button>
        </div>
      )}

      <InstallationDetailModal
        installationId={detailId}
        onClose={() => setDetailId(null)}
        onChanged={() => {
          refetchList();
          refetchStats();
        }}
      />
    </div>
  );
}
