"use client";

import { useCallback, useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { Pencil, Trash2 } from "lucide-react";
import MainTitle from "@/components/layout/dashboard/main-title";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import DataService from "@/config/axios";
import { useRequireSuperAdmin } from "@/hooks/use-require-super-admin";
import { getApiErrorMessage } from "@/lib/api-error";
import { uploadAdminProductImage } from "@/lib/upload-admin-product-image";
import { BlogRichTextEditor } from "@/features/super-admin/blogs/blog-rich-text-editor";
import { toast } from "sonner";

type Category = {
  _id: string;
  name: string;
  slug: string;
  description?: string;
  parent?: { _id: string; name: string; slug: string } | null;
  icon?: string;
  banner?: string;
  metaTitle?: string;
  metaDescription?: string;
  metaKeywords?: string[];
};
type Product = {
  _id: string;
  title: string;
  slug: string;
  price: number;
  salePrice?: number | null;
  shippingCost?: number;
  status: "draft" | "published";
  categories?: { _id: string; name: string }[];
};

function getFileLabelFromUrl(url: string) {
  if (!url) return "";
  try {
    const parsed = new URL(url);
    const part = parsed.pathname.split("/").filter(Boolean).pop();
    return part || url;
  } catch {
    return url;
  }
}

export default function AdminProductsBlock() {
  const ready = useRequireSuperAdmin();
  const params = useParams();
  const app = params.app as string;

  const [loading, setLoading] = useState(true);
  const [categories, setCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [openCategory, setOpenCategory] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [categorySaving, setCategorySaving] = useState(false);
  const [iconUploading, setIconUploading] = useState(false);
  const [bannerUploading, setBannerUploading] = useState(false);
  const [categoryForm, setCategoryForm] = useState({
    name: "",
    parent: "",
    description: "",
    slug: "",
    icon: "",
    banner: "",
    metaTitle: "",
    metaDescription: "",
    metaKeywords: "",
  });

  const load = useCallback(async () => {
    try {
      const [cats, rows] = await Promise.all([
        DataService.get("/admin/product-categories"),
        DataService.get("/admin/products"),
      ]);
      setCategories(cats.data?.data || []);
      setProducts(rows.data?.data || []);
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Failed to load product data"));
    } finally {
      setLoading(false);
    }
  }, []);

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

  const resetCategoryForm = () => {
    setEditingCategory(null);
    setCategoryForm({
      name: "",
      parent: "",
      description: "",
      slug: "",
      icon: "",
      banner: "",
      metaTitle: "",
      metaDescription: "",
      metaKeywords: "",
    });
  };

  const onUploadCategoryImage = async (
    e: React.ChangeEvent<HTMLInputElement>,
    field: "icon" | "banner",
  ) => {
    const file = e.target.files?.[0];
    e.target.value = "";
    if (!file) return;
    try {
      if (field === "icon") setIconUploading(true);
      else setBannerUploading(true);
      const url = await uploadAdminProductImage(file);
      setCategoryForm((prev) => ({ ...prev, [field]: url }));
      toast.success(`${field === "icon" ? "Icon" : "Banner"} uploaded`);
    } catch (err: unknown) {
      toast.error(err instanceof Error ? err.message : "Upload failed");
    } finally {
      if (field === "icon") setIconUploading(false);
      else setBannerUploading(false);
    }
  };

  const saveCategory = async () => {
    try {
      if (!categoryForm.name.trim()) {
        toast.error("Category name is required");
        return;
      }
      if (editingCategory && categoryForm.parent && categoryForm.parent === editingCategory._id) {
        toast.error("Category cannot be parent of itself");
        return;
      }
      const payload = {
        name: categoryForm.name.trim(),
        parent: categoryForm.parent || null,
        description: categoryForm.description.trim(),
        slug: categoryForm.slug.trim(),
        icon: categoryForm.icon.trim(),
        banner: categoryForm.banner.trim(),
        metaTitle: categoryForm.metaTitle.trim(),
        metaDescription: categoryForm.metaDescription.trim(),
        metaKeywords: categoryForm.metaKeywords
          .split(",")
          .map((item) => item.trim())
          .filter(Boolean),
      };
      setCategorySaving(true);
      if (editingCategory) {
        await DataService.patch(`/admin/product-categories/${editingCategory._id}`, payload);
        toast.success("Category updated");
      } else {
        await DataService.post("/admin/product-categories", payload);
        toast.success("Category created");
      }
      setOpenCategory(false);
      resetCategoryForm();
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not save category"));
    } finally {
      setCategorySaving(false);
    }
  };

  const removeCategory = async (category: Category) => {
    if (!confirm(`Delete category "${category.name}"?`)) return;
    try {
      await DataService.delete(`/admin/product-categories/${category._id}`);
      toast.success("Category deleted");
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not delete category"));
    }
  };

  const removeProduct = async (product: Product) => {
    if (!confirm(`Delete product "${product.title}"?`)) return;
    try {
      await DataService.delete(`/admin/products/${product._id}`);
      toast.success("Product deleted");
      load();
    } catch (e: unknown) {
      toast.error(getApiErrorMessage(e, "Could not delete product"));
    }
  };

  if (!ready || loading) {
    return <div className="rounded-md border bg-white p-8 text-center text-gray-500">Loading…</div>;
  }

  return (
    <div className="space-y-6">
      <MainTitle title="Product management (Super admin)" />

      <Tabs defaultValue="categories" className="w-full">
        <TabsList className="mb-4 w-full sm:w-auto">
          <TabsTrigger value="categories">Categories</TabsTrigger>
          <TabsTrigger value="products">Products</TabsTrigger>
        </TabsList>

        <TabsContent value="categories" className="mt-0 space-y-4">
          <div className="flex justify-end">
            <Button
              variant="outline"
              onClick={() => {
                resetCategoryForm();
                setOpenCategory(true);
              }}
            >
              Add category
            </Button>
          </div>
          <div className="rounded-md border bg-white">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Category</TableHead>
                  <TableHead>Parent</TableHead>
                  <TableHead>Slug</TableHead>
                  <TableHead className="w-[100px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {categories.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={4} className="text-center text-gray-400">
                      No categories yet.
                    </TableCell>
                  </TableRow>
                ) : (
                  categories.map((c) => (
                    <TableRow key={c._id}>
                      <TableCell>{c.name}</TableCell>
                      <TableCell>{c.parent?.name || "—"}</TableCell>
                      <TableCell>{c.slug}</TableCell>
                      <TableCell className="flex gap-2">
                        <Button
                          variant="outline"
                          size="icon"
                          onClick={() => {
                            setEditingCategory(c);
                            setCategoryForm({
                              name: c.name,
                              parent: c.parent?._id || "",
                              description: c.description || "",
                              slug: c.slug || "",
                              icon: c.icon || "",
                              banner: c.banner || "",
                              metaTitle: c.metaTitle || "",
                              metaDescription: c.metaDescription || "",
                              metaKeywords: Array.isArray(c.metaKeywords)
                                ? c.metaKeywords.join(", ")
                                : "",
                            });
                            setOpenCategory(true);
                          }}
                        >
                          <Pencil className="size-4" />
                        </Button>
                        <Button variant="outline" size="icon" onClick={() => removeCategory(c)}>
                          <Trash2 className="size-4 text-red-600" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </TabsContent>

        <TabsContent value="products" className="mt-0 space-y-4">
          <div className="flex justify-end">
            <Button asChild>
              <Link href={`/${app}/admin/products/new`}>Add product</Link>
            </Button>
          </div>
          <div className="rounded-md border bg-white">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Title</TableHead>
                  <TableHead>Price</TableHead>
                  <TableHead>Shipping</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="w-[100px]" />
                </TableRow>
              </TableHeader>
              <TableBody>
                {products.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="text-center text-gray-400">
                      No products yet.
                    </TableCell>
                  </TableRow>
                ) : (
                  products.map((p) => (
                    <TableRow key={p._id}>
                      <TableCell className="font-medium">{p.title}</TableCell>
                      <TableCell>
                        {p.salePrice != null && p.salePrice >= 0 ? (
                          <span>
                            <span className="text-primary font-semibold">{p.salePrice}</span>
                            <span className="ml-2 text-gray-400 line-through">{p.price}</span>
                          </span>
                        ) : (
                          p.price
                        )}
                      </TableCell>
                      <TableCell>{p.shippingCost ?? 0}</TableCell>
                      <TableCell className="capitalize">{p.status}</TableCell>
                      <TableCell className="flex gap-2">
                        <Button variant="outline" size="icon" asChild>
                          <Link href={`/${app}/admin/products/${p._id}/edit`} aria-label="Edit product">
                            <Pencil className="size-4" />
                          </Link>
                        </Button>
                        <Button variant="outline" size="icon" onClick={() => removeProduct(p)}>
                          <Trash2 className="size-4 text-red-600" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </TabsContent>
      </Tabs>

      <Dialog open={openCategory} onOpenChange={setOpenCategory}>
        <DialogContent className="max-h-[90vh] overflow-y-auto sm:max-w-2xl">
          <DialogHeader>
            <DialogTitle>{editingCategory ? "Edit category" : "Add category"}</DialogTitle>
          </DialogHeader>
          <div className="grid gap-3">
            <div className="grid gap-2">
              <Label>Category name</Label>
              <Input
                value={categoryForm.name}
                onChange={(e) => setCategoryForm((prev) => ({ ...prev, name: e.target.value }))}
              />
            </div>
            <div className="grid gap-2">
              <Label>Parent</Label>
              <select
                className="h-10 rounded-md border bg-background px-3 text-sm"
                value={categoryForm.parent}
                onChange={(e) => setCategoryForm((prev) => ({ ...prev, parent: e.target.value }))}
              >
                <option value="">None (top-level)</option>
                {categories
                  .filter((c) => !editingCategory || c._id !== editingCategory._id)
                  .map((c) => (
                    <option key={c._id} value={c._id}>
                      {c.name}
                    </option>
                  ))}
              </select>
            </div>
            <div className="grid gap-2">
              <Label>Description</Label>
              <BlogRichTextEditor
                value={categoryForm.description}
                onChange={(html) => setCategoryForm((prev) => ({ ...prev, description: html }))}
                placeholder="Category description..."
              />
            </div>
            <div className="grid gap-2">
              <Label>Slug</Label>
              <Input
                placeholder="Leave empty to auto-generate from name"
                value={categoryForm.slug}
                onChange={(e) => setCategoryForm((prev) => ({ ...prev, slug: e.target.value }))}
              />
            </div>
            <div className="grid gap-2">
              <Label>Icon</Label>
              <div className="flex flex-wrap gap-2">
                <Input
                  readOnly
                  value={categoryForm.icon ? getFileLabelFromUrl(categoryForm.icon) : "No icon selected"}
                />
                <label className="inline-flex h-10 cursor-pointer items-center rounded-md border px-3 text-sm">
                  {iconUploading
                    ? "Uploading..."
                    : categoryForm.icon
                      ? "Change"
                      : "Upload"}
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={(e) => onUploadCategoryImage(e, "icon")}
                  />
                </label>
                {categoryForm.icon ? (
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setCategoryForm((prev) => ({ ...prev, icon: "" }))}
                  >
                    Delete
                  </Button>
                ) : null}
              </div>
            </div>
            <div className="grid gap-2">
              <Label>Banner</Label>
              <div className="flex flex-wrap gap-2">
                <Input
                  readOnly
                  value={categoryForm.banner ? getFileLabelFromUrl(categoryForm.banner) : "No banner selected"}
                />
                <label className="inline-flex h-10 cursor-pointer items-center rounded-md border px-3 text-sm">
                  {bannerUploading
                    ? "Uploading..."
                    : categoryForm.banner
                      ? "Change"
                      : "Upload"}
                  <input
                    type="file"
                    accept="image/*"
                    className="hidden"
                    onChange={(e) => onUploadCategoryImage(e, "banner")}
                  />
                </label>
                {categoryForm.banner ? (
                  <Button
                    type="button"
                    variant="outline"
                    onClick={() => setCategoryForm((prev) => ({ ...prev, banner: "" }))}
                  >
                    Delete
                  </Button>
                ) : null}
              </div>
            </div>
            <div className="grid gap-2">
              <Label>Meta title</Label>
              <Input
                value={categoryForm.metaTitle}
                onChange={(e) => setCategoryForm((prev) => ({ ...prev, metaTitle: e.target.value }))}
              />
            </div>
            <div className="grid gap-2">
              <Label>Meta description</Label>
              <Textarea
                value={categoryForm.metaDescription}
                onChange={(e) =>
                  setCategoryForm((prev) => ({ ...prev, metaDescription: e.target.value }))
                }
              />
            </div>
            <div className="grid gap-2">
              <Label>Meta keywords</Label>
              <Input
                placeholder="keyword1, keyword2"
                value={categoryForm.metaKeywords}
                onChange={(e) =>
                  setCategoryForm((prev) => ({ ...prev, metaKeywords: e.target.value }))
                }
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpenCategory(false)}>
              Cancel
            </Button>
            <Button onClick={saveCategory} disabled={categorySaving}>
              {categorySaving ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
