"use client";

import { faPlus, faStore } from "@fortawesome/free-solid-svg-icons";
import Image from "next/image";
import { useEffect, useState } from "react";
import Toast from "@/components/ui/Toast";
import { useAdminToast } from "@/hooks/admin/useAdminToast";
import { useImageUpload } from "@/hooks/admin/useImageUpload";
import AdminCard from "@/components/admin/AdminCard";
import AdminInput from "@/components/admin/AdminInput";
import AdminTextarea from "@/components/admin/AdminTextarea";
import AdminButton from "@/components/admin/AdminButton";
import AdminDataGrid from "@/components/admin/AdminDataGrid";
import AdminEmptyState from "@/components/admin/AdminEmptyState";
import AdminConfirmDialog from "@/components/admin/AdminConfirmDialog";
import AdminFormModal from "@/components/admin/AdminFormModal";
import AdminEditDeleteButtons from "@/components/admin/AdminEditDeleteButtons";
import AdminLoadingState from "@/components/admin/AdminLoadingState";
import ImageUpload from "@/components/ui/ImageUpload";
import { adminFetch } from "@/lib/adminFetch";

interface BoldProduct {
  id?: number;
  name: string;
  description: string;
  link: string;
  image: string | null;
}

const DESCRIPTION_LIMIT = 80;

export default function BoldTab() {
  const [products, setProducts] = useState<BoldProduct[]>([]);
  const [newProduct, setNewProduct] = useState<BoldProduct>({
    name: "",
    description: "",
    link: "",
    image: null,
  });
  const [editingId, setEditingId] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);
  const [showEditor, setShowEditor] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState<{
    isOpen: boolean;
    id: number | null;
  }>({ isOpen: false, id: null });
  const { toast, showSuccess, showError, hideToast } = useAdminToast();
  const { uploadImage, deleteImage, isUploading } = useImageUpload({
    onUploadSuccess: (url) => setNewProduct((p) => ({ ...p, image: url })),
    onDeleteSuccess: () => setNewProduct((p) => ({ ...p, image: null })),
  });

  useEffect(() => {
    let cancelled = false;
    fetch("/api/bold")
      .then((res) => res.json())
      .then((data) => {
        if (!cancelled) {
          setProducts(data);
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          showError("Failed to load products");
          setLoading(false);
        }
      });
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const resetForm = () => {
    setNewProduct({ name: "", description: "", link: "", image: null });
    setEditingId(null);
    setShowEditor(false);
  };

  const handleSubmit = async () => {
    try {
      const formData = new FormData();
      if (editingId) formData.append("id", editingId.toString());
      formData.append("name", newProduct.name);
      formData.append("description", newProduct.description);
      formData.append("link", newProduct.link);
      if (newProduct.image) formData.append("image", newProduct.image);

      const res = await adminFetch("/api/bold", { method: "POST", body: formData });
      if (!res.ok) throw new Error();
      const saved = await res.json();

      setProducts((prev) =>
        editingId ? prev.map((p) => (p.id === saved.id ? saved : p)) : [...prev, saved],
      );
      showSuccess(
        editingId ? "Product updated successfully!" : "Product added successfully!",
      );
      resetForm();
    } catch {
      showError("Failed to save product. Please try again.");
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await adminFetch("/api/bold", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id }),
      });
      if (!res.ok) throw new Error();
      setProducts((prev) => prev.filter((p) => p.id !== id));
      showSuccess("Product deleted successfully!");
    } catch {
      showError("Failed to delete product. Please try again.");
    } finally {
      setDeleteConfirm({ isOpen: false, id: null });
    }
  };

  const startEdit = (product: BoldProduct) => {
    setNewProduct({ ...product });
    setEditingId(product.id!);
    setShowEditor(true);
  };

  if (loading) return <AdminLoadingState message="Loading products..." />;

  const getImgSrc = (src: string) =>
    src.replace("/uploads/", "/api/uploads/").replace(/\.(jpg|jpeg|png)$/i, ".webp");

  return (
    <>
      {toast && <Toast message={toast.message} type={toast.type} onClose={hideToast} />}

      <AdminConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, id: null })}
        onConfirm={() => deleteConfirm.id && handleDelete(deleteConfirm.id)}
        title="Delete product"
        message="Are you sure you want to delete this product? This action cannot be undone."
      />

      <AdminCard
        header={
          <div className="flex items-center justify-between">
            <div>
              <h3 className="text-sm font-semibold text-slate-100">Bold products</h3>
              <p className="text-xs text-slate-400">Featured product listings</p>
            </div>
            <AdminButton
              variant="primary"
              size="sm"
              icon={faPlus}
              onClick={() => {
                setEditingId(null);
                setNewProduct({ name: "", description: "", link: "", image: null });
                setShowEditor(true);
              }}
            >
              Add product
            </AdminButton>
          </div>
        }
      >
        {products.length === 0 ? (
          <AdminEmptyState
            title="No products yet"
            description="Add your first Bold product to get started"
            icon={faStore}
            action={{ label: "Add product", onClick: () => setShowEditor(true) }}
          />
        ) : (
          <AdminDataGrid columns={2} gap="md">
            {products.map((product) => (
              <div
                key={product.id}
                className="group relative flex gap-4 rounded-lg border border-slate-800 bg-slate-900/60 p-4"
              >
                {product.image && typeof product.image === "string" && (
                  <Image
                    src={getImgSrc(product.image)}
                    alt={product.name}
                    width={96}
                    height={96}
                    className="h-24 w-24 shrink-0 rounded-lg object-cover"
                  />
                )}
                <div className="min-w-0 flex-1">
                  <h3 className="truncate text-sm font-semibold text-slate-100">
                    {product.name}
                  </h3>
                  <p className="mb-1.5 line-clamp-2 text-xs text-slate-400">
                    {product.description}
                  </p>
                  <a
                    href={product.link}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="truncate block text-xs text-indigo-400 hover:text-indigo-300 hover:underline"
                  >
                    {product.link}
                  </a>
                </div>
                <div className="opacity-0 transition-opacity group-hover:opacity-100">
                  <AdminEditDeleteButtons
                    onEdit={() => startEdit(product)}
                    onDelete={() =>
                      setDeleteConfirm({ isOpen: true, id: product.id! })
                    }
                  />
                </div>
              </div>
            ))}
          </AdminDataGrid>
        )}
      </AdminCard>

      <AdminFormModal
        isOpen={showEditor}
        onClose={resetForm}
        title={editingId ? "Edit product" : "Add new product"}
        onSubmit={handleSubmit}
        submitLabel={editingId ? "Save changes" : "Add product"}
        size="lg"
      >
        <div className="grid grid-cols-1 gap-5 lg:grid-cols-2">
          <div className="space-y-4">
            <AdminInput
              label="Product name"
              placeholder="Enter product name"
              value={newProduct.name}
              onChange={(e) => setNewProduct({ ...newProduct, name: e.target.value })}
              required
            />
            <AdminTextarea
              label="Product description"
              placeholder="Short description"
              value={newProduct.description}
              onChange={(e) =>
                setNewProduct({ ...newProduct, description: e.target.value })
              }
              maxLength={DESCRIPTION_LIMIT}
              showCharacterCount
              rows={3}
            />
            <AdminInput
              label="Product link"
              type="url"
              placeholder="https://example.com"
              value={newProduct.link}
              onChange={(e) => setNewProduct({ ...newProduct, link: e.target.value })}
              required
            />
          </div>
          <div>
            <label className="mb-1.5 block text-sm font-medium text-slate-300">
              Product image
            </label>
            <ImageUpload
              onImageUpload={async (file) => {
                await uploadImage(file);
              }}
              onImageDelete={async () => {
                if (newProduct.image) {
                  await deleteImage(newProduct.image);
                }
              }}
              currentImage={newProduct.image}
              disabled={isUploading}
              className="w-full"
            />
          </div>
        </div>
      </AdminFormModal>
    </>
  );
}
