"use client";

import { useState, useEffect, useCallback, startTransition } from "react";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { ChevronDown, RefreshCw } from "lucide-react";
import { toast } from "sonner";
import { adminListOrders, adminUpdateOrderStatus, AdminOrderApi } from "@/lib/api/orders";
import { useLanguage } from "@/contexts/LanguageContext";
import { ApiError } from "@/lib/api";

type Status = "all" | "pending" | "paid" | "shipped" | "delivered" | "cancelled" | "refunded";

const NEXT_STATUSES: Record<string, string[]> = {
  pending:   ["paid", "cancelled"],
  paid:      ["shipped", "cancelled"],
  shipped:   ["delivered"],
  delivered: [],
  cancelled: [],
  refunded:  [],
};

export default function AdminCommandes() {
  const { t, locale } = useLanguage();
  const [orders, setOrders] = useState<AdminOrderApi[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<Status>("all");
  const [updating, setUpdating] = useState<string | null>(null);

  const STATUS_CONFIG: Record<string, { label: string; variant: "default" | "secondary" | "destructive" | "outline" }> = {
    pending:   { label: t("admin.status.pending"),   variant: "secondary" },
    paid:      { label: t("admin.status.paid"),      variant: "default" },
    shipped:   { label: t("admin.status.shipped"),   variant: "outline" },
    delivered: { label: t("admin.status.delivered"), variant: "default" },
    cancelled: { label: t("admin.status.cancelled"), variant: "destructive" },
    refunded:  { label: t("admin.status.refunded"),  variant: "destructive" },
  };

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await adminListOrders(filter === "all" ? undefined : filter);
      setOrders(res.data);
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : t("admin.error"));
    } finally {
      setLoading(false);
    }
  }, [filter]);

  useEffect(() => { startTransition(() => load()); }, [load]);

  const handleStatus = async (id: string, status: string) => {
    setUpdating(id);
    try {
      await adminUpdateOrderStatus(id, status);
      setOrders((prev) => prev.map((o) => (o.id === id ? { ...o, status } : o)));
      toast.success(t("admin.settings.saved"));
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : t("admin.error"));
    } finally {
      setUpdating(null);
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="font-serif text-2xl font-semibold">{t("admin.orders.title")}</h2>
          <p className="text-sm text-muted-foreground mt-1">{orders.length} {t("admin.orders.subtitle")}</p>
        </div>
        <Button variant="outline" size="sm" onClick={load} disabled={loading}>
          <RefreshCw className={`h-4 w-4 mr-2 ${loading ? "animate-spin" : ""}`} />
          {t("admin.refresh")}
        </Button>
      </div>

      <Tabs value={filter} onValueChange={(v) => setFilter(v as Status)}>
        <TabsList className="flex-wrap">
          <TabsTrigger value="all">{t("admin.orders.tab_all")}</TabsTrigger>
          <TabsTrigger value="pending">{t("admin.orders.tab_pending")}</TabsTrigger>
          <TabsTrigger value="paid">{t("admin.orders.tab_paid")}</TabsTrigger>
          <TabsTrigger value="shipped">{t("admin.orders.tab_shipped")}</TabsTrigger>
          <TabsTrigger value="delivered">{t("admin.orders.tab_delivered")}</TabsTrigger>
          <TabsTrigger value="cancelled">{t("admin.orders.tab_cancelled")}</TabsTrigger>
        </TabsList>
      </Tabs>

      <Card>
        {loading ? (
          <div className="p-8 space-y-3">
            {Array.from({ length: 5 }).map((_, i) => (
              <div key={i} className="h-12 bg-muted animate-pulse rounded" />
            ))}
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>{t("admin.orders.col_ref")}</TableHead>
                <TableHead>{t("admin.orders.col_customer")}</TableHead>
                <TableHead>{t("admin.orders.col_date")}</TableHead>
                <TableHead>{t("admin.orders.col_total")}</TableHead>
                <TableHead>{t("admin.status")}</TableHead>
                <TableHead className="text-right">{t("admin.actions")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {orders.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center text-muted-foreground py-8">
                    {t("admin.orders.none")}
                  </TableCell>
                </TableRow>
              ) : (
                orders.map((o) => {
                  const cfg = STATUS_CONFIG[o.status] ?? { label: o.status, variant: "outline" as const };
                  const nextStatuses = NEXT_STATUSES[o.status] ?? [];
                  return (
                    <TableRow key={o.id}>
                      <TableCell className="font-mono text-xs text-muted-foreground">
                        #{o.id.slice(0, 8).toUpperCase()}
                      </TableCell>
                      <TableCell>
                        <div className="font-medium text-sm">{o.client_name ?? "—"}</div>
                        <div className="text-xs text-muted-foreground">{o.client_email ?? ""}</div>
                      </TableCell>
                      <TableCell className="text-sm">
                        {new Date(o.created_at).toLocaleDateString(locale, { day: "2-digit", month: "short", year: "numeric" })}
                      </TableCell>
                      <TableCell className="font-semibold">{o.total_amount.toFixed(2)} €</TableCell>
                      <TableCell>
                        <Badge variant={cfg.variant}>{cfg.label}</Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        {nextStatuses.length > 0 ? (
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="outline" size="sm" disabled={updating === o.id}>
                                {t("admin.orders.update_btn")} <ChevronDown className="h-3 w-3 ml-1" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              {nextStatuses.map((s) => (
                                <DropdownMenuItem key={s} onClick={() => handleStatus(o.id, s)}>
                                  {STATUS_CONFIG[s]?.label ?? s}
                                </DropdownMenuItem>
                              ))}
                            </DropdownMenuContent>
                          </DropdownMenu>
                        ) : (
                          <span className="text-xs text-muted-foreground">—</span>
                        )}
                      </TableCell>
                    </TableRow>
                  );
                })
              )}
            </TableBody>
          </Table>
        )}
      </Card>
    </div>
  );
}
