"use client";

import { useState, useRef } from "react";
import { Plus, Pencil, Trash2, Upload, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from "@/components/ui/table";
import {
  Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogDescription,
} from "@/components/ui/dialog";
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from "@/components/ui/select";
import { useAdmin } from "@/contexts/AdminContext";
import { useLanguage } from "@/contexts/LanguageContext";
import { ApiError } from "@/lib/api";
import { adminUploadProductImage } from "@/lib/api/products";
import { Product } from "@/data/products";
import { toast } from "sonner";

type FormState = {
  name: string;
  category: Product["category"];
  price: string;
  original_price: string;
  stock_quantity: string;
  description: string;
  colors: string;
  lengths: string;
  isNew: boolean;
  isBestseller: boolean;
};

const emptyForm: FormState = {
  name: "",
  category: "clip-in",
  price: "",
  original_price: "",
  stock_quantity: "0",
  description: "",
  colors: "",
  lengths: "",
  isNew: false,
  isBestseller: false,
};

export default function AdminProducts() {
  const { products, productsLoading, addProduct, updateProduct, deleteProduct, refreshProducts } = useAdmin();
  const { t } = useLanguage();
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [form, setForm] = useState<FormState>(emptyForm);
  const [deleteId, setDeleteId] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const categoryLabels: Record<Product["category"], string> = {
    "clip-in": "Clip-In",
    "tape-in": "Tape-In",
    "ponytail": "Ponytail",
    "keratin": t("admin.products.category") === "Kategorie" ? "Keratin" : t("admin.products.category") === "Category" ? "Keratin" : "Kératine",
  };

  const openCreate = () => {
    setEditingId(null);
    setForm(emptyForm);
    setImageFile(null);
    setImagePreview(null);
    setDialogOpen(true);
  };

  const openEdit = (p: Product) => {
    setEditingId(p.id);
    setForm({
      name: p.name,
      category: p.category,
      price: String(p.price),
      original_price: p.originalPrice ? String(p.originalPrice) : "",
      stock_quantity: String(p.stockQuantity ?? 0),
      description: p.description,
      colors: p.colors.join(", "),
      lengths: p.lengths.join(", "),
      isNew: !!p.isNew,
      isBestseller: !!p.isBestseller,
    });
    setImageFile(null);
    setImagePreview(p.image || null);
    setDialogOpen(true);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setImageFile(file);
    setImagePreview(URL.createObjectURL(file));
  };

  const clearImage = () => {
    setImageFile(null);
    setImagePreview(null);
    if (fileInputRef.current) fileInputRef.current.value = "";
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    const price = parseFloat(form.price);
    if (!form.name || isNaN(price)) {
      toast.error(t("admin.products.valid_required"));
      return;
    }

    const payload = {
      name: form.name,
      category: form.category,
      price,
      original_price: form.original_price ? parseFloat(form.original_price) : undefined,
      stock_quantity: parseInt(form.stock_quantity) || 0,
      colors: form.colors.split(",").map((c) => c.trim()).filter(Boolean),
      lengths: form.lengths.split(",").map((l) => l.trim()).filter(Boolean),
      description: form.description,
      features: [],
      is_new: form.isNew,
      is_bestseller: form.isBestseller,
    };

    setSaving(true);
    try {
      let savedId = editingId;
      if (editingId) {
        await updateProduct(editingId, payload);
      } else {
        const created = await addProduct(payload);
        savedId = created.id;
      }
      if (imageFile && savedId) {
        await adminUploadProductImage(savedId, imageFile);
        await refreshProducts();
      }
      toast.success(editingId ? t("admin.products.saved") : t("admin.products.added"));
      setDialogOpen(false);
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : t("admin.products.save_error"));
    } finally {
      setSaving(false);
    }
  };

  const handleDelete = async () => {
    if (!deleteId) return;
    try {
      await deleteProduct(deleteId);
      toast.success(t("admin.products.deleted"));
    } catch (err) {
      toast.error(err instanceof ApiError ? err.message : t("admin.products.delete_error"));
    } finally {
      setDeleteId(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.products.title")}</h2>
          <p className="text-sm text-muted-foreground mt-1">
            {products.length} {t("admin.products.subtitle")}
          </p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="h-4 w-4" />
          {t("admin.add")}
        </Button>
      </div>

      <Card>
        {productsLoading ? (
          <div className="p-8 space-y-3">
            {Array.from({ length: 4 }).map((_, i) => (
              <div key={i} className="h-12 bg-muted animate-pulse rounded" />
            ))}
          </div>
        ) : (
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-16">{t("admin.products.col_image")}</TableHead>
                <TableHead>{t("admin.products.col_name")}</TableHead>
                <TableHead>{t("admin.products.col_category")}</TableHead>
                <TableHead>{t("admin.products.col_price")}</TableHead>
                <TableHead className="text-center">{t("admin.products.col_stock")}</TableHead>
                <TableHead>{t("admin.products.col_status")}</TableHead>
                <TableHead className="text-right">{t("admin.actions")}</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {products.map((p) => (
                <TableRow key={p.id}>
                  <TableCell>
                    {p.image ? (
                      <img src={p.image} alt={p.name} className="h-12 w-12 rounded object-cover" />
                    ) : (
                      <div className="h-12 w-12 rounded bg-muted flex items-center justify-center">
                        <Upload className="h-4 w-4 text-muted-foreground" />
                      </div>
                    )}
                  </TableCell>
                  <TableCell className="font-medium">{p.name}</TableCell>
                  <TableCell className="text-muted-foreground">{categoryLabels[p.category]}</TableCell>
                  <TableCell>{p.price} €</TableCell>
                  <TableCell className="text-center">
                    <span className={p.stockQuantity === 0 ? "text-destructive font-medium" : ""}>{p.stockQuantity ?? 0}</span>
                  </TableCell>
                  <TableCell className="space-x-1">
                    {p.isNew && <Badge variant="secondary">{t("admin.products.badge_new")}</Badge>}
                    {p.isBestseller && <Badge>Bestseller</Badge>}
                  </TableCell>
                  <TableCell className="text-right space-x-2">
                    <Button variant="ghost" size="icon" onClick={() => openEdit(p)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" onClick={() => setDeleteId(p.id)}>
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        )}
      </Card>

      <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <DialogContent className="lg:min-w-2xl max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>{editingId ? t("admin.products.edit_title") : t("admin.products.create_title")}</DialogTitle>
            <DialogDescription>{t("admin.products.form_desc")}</DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2 col-span-2">
                <Label htmlFor="name">{t("admin.products.name")}</Label>
                <Input id="name" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} required />
              </div>
              <div className="space-y-2">
                <Label>{t("admin.products.category")}</Label>
                <Select value={form.category} onValueChange={(v) => setForm({ ...form, category: v as Product["category"] })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="clip-in">Clip-In</SelectItem>
                    <SelectItem value="tape-in">Tape-In</SelectItem>
                    <SelectItem value="ponytail">Ponytail</SelectItem>
                    <SelectItem value="keratin">Kératine</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label htmlFor="price">{t("admin.products.price")}</Label>
                <Input id="price" type="number" step="0.01" value={form.price} onChange={(e) => setForm({ ...form, price: e.target.value })} required />
              </div>
              <div className="space-y-2">
                <Label htmlFor="original_price">{t("admin.products.original_price")}</Label>
                <Input id="original_price" type="number" step="0.01" value={form.original_price} onChange={(e) => setForm({ ...form, original_price: e.target.value })} placeholder={t("admin.products.optional")} />
              </div>
              <div className="space-y-2 col-span-2">
                <Label htmlFor="stock_quantity">{t("admin.products.stock_quantity")}</Label>
                <Input id="stock_quantity" type="number" min="0" step="1" value={form.stock_quantity} onChange={(e) => setForm({ ...form, stock_quantity: e.target.value })} />
              </div>
              <div className="space-y-2 col-span-2">
                <Label>{t("admin.products.image")}</Label>
                <div className="flex items-start gap-4">
                  {imagePreview && (
                    <div className="relative shrink-0">
                      <img src={imagePreview} alt="preview" className="h-24 w-24 rounded object-cover border border-border" />
                      {imageFile && (
                        <button type="button" onClick={clearImage} className="absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-0.5">
                          <X className="h-3 w-3" />
                        </button>
                      )}
                    </div>
                  )}
                  <div className="flex-1">
                    <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={handleFileChange} />
                    <Button type="button" variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
                      <Upload className="h-4 w-4 mr-2" />
                      {imagePreview ? t("admin.products.change_image") : t("admin.products.choose_image")}
                    </Button>
                    {imageFile && <p className="text-xs text-muted-foreground mt-1.5">{imageFile.name}</p>}
                  </div>
                </div>
              </div>
              <div className="space-y-2 col-span-2">
                <Label htmlFor="description">{t("admin.products.description")}</Label>
                <Textarea id="description" value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} rows={3} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="colors">{t("admin.products.colors")}</Label>
                <Input id="colors" value={form.colors} onChange={(e) => setForm({ ...form, colors: e.target.value })} placeholder="Brun, Blond, Noir" />
              </div>
              <div className="space-y-2">
                <Label htmlFor="lengths">{t("admin.products.lengths")}</Label>
                <Input id="lengths" value={form.lengths} onChange={(e) => setForm({ ...form, lengths: e.target.value })} placeholder="40 cm, 50 cm" />
              </div>
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" checked={form.isNew} onChange={(e) => setForm({ ...form, isNew: e.target.checked })} />
                {t("admin.products.mark_new")}
              </label>
              <label className="flex items-center gap-2 text-sm">
                <input type="checkbox" checked={form.isBestseller} onChange={(e) => setForm({ ...form, isBestseller: e.target.checked })} />
                {t("admin.products.mark_bestseller")}
              </label>
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setDialogOpen(false)}>{t("admin.cancel")}</Button>
              <Button type="submit" disabled={saving}>{saving ? t("admin.saving") : editingId ? t("admin.save") : t("admin.create")}</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      <AlertDialog open={!!deleteId} onOpenChange={(o) => !o && setDeleteId(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("admin.products.delete_title")}</AlertDialogTitle>
            <AlertDialogDescription>{t("admin.irreversible")}</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t("admin.cancel")}</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete}>{t("admin.delete")}</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
