// react
import React, { useState, useEffect } from "react";
// application
import AdminLayout from "~/components/AdminLayout";
import ProtectedRoute from "~/components/ProtectedRoute";
import ProductList from "~/components/products/ProductList";
import ProductForm from "~/components/products/ProductForm";
import { IProduct } from "~/interfaces/product";
import { productsApi } from "~/services/productsApi";
import { toast } from "react-toastify";
import { IModel } from "~/interfaces/vehicle";
import { vehiclesApi } from "~/services/vehiclesApi";

function ProductosPage() {
  const [products, setProducts] = useState<IProduct[]>([]);
  const [allProducts, setAllProducts] = useState<IProduct[]>([]);
  const [selectedProductIds, setSelectedProductIds] = useState<number[]>([]);
  const [selectAllMode, setSelectAllMode] = useState(false);
  const [excludedProductIds, setExcludedProductIds] = useState<number[]>([]);
  const [editingProduct, setEditingProduct] = useState<IProduct | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [loading, setLoading] = useState(true);
  const [searchLoading, setSearchLoading] = useState(false);
  const [models, setModels] = useState<IModel[]>([]);
  const [showModelFilter, setShowModelFilter] = useState(false);
  const [modelFilterDraft, setModelFilterDraft] = useState<number | null>(null);
  const [appliedModelFilter, setAppliedModelFilter] = useState<number | null>(null);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalProductsInDb, setTotalProductsInDb] = useState(0);
  const [totalFiltered, setTotalFiltered] = useState(0);
  const [searchTerm, setSearchTerm] = useState("");

  const clearSelection = () => {
    setSelectAllMode(false);
    setExcludedProductIds([]);
    setSelectedProductIds([]);
  };

  const getSelectionScopeTotal = () => {
    if (searchTerm.trim()) {
      return products.filter((p) => typeof p.id === "number").length;
    }
    if (appliedModelFilter) {
      return totalFiltered;
    }
    return totalProductsInDb;
  };

  const isProductSelected = (id: number) =>
    selectAllMode
      ? !excludedProductIds.includes(id)
      : selectedProductIds.includes(id);

  const getSelectedCount = () => {
    if (selectAllMode) {
      return Math.max(0, getSelectionScopeTotal() - excludedProductIds.length);
    }
    return selectedProductIds.length;
  };

  const loadProducts = async () => {
    try {
      setLoading(true);
      const res = await productsApi.getAll(page, 20, undefined, undefined, undefined, appliedModelFilter);

      setAllProducts(res.data);
      setProducts(res.data);
      setTotalProductsInDb(res.count);
      setTotalFiltered(res.totalFiltered ?? res.data.length);
      if (res.pagination) {
        setTotalPages(res.pagination.total_pages);
      }
    } catch (error: any) {
      toast.error(error.message || "Error al cargar productos");
    } finally {
      setLoading(false);
    }
  };

  const handleSearchSubmit = async () => {
    const term = searchTerm.trim();
    if (!term) {
      setProducts(allProducts);
      return;
    }
    try {
      setSearchLoading(true);
      clearSelection();
      const res = await productsApi.search(term, appliedModelFilter);
      setProducts(res.data);
    } catch (error: any) {
      toast.error(error.message || "Error al buscar productos");
      setProducts([]);
    } finally {
      setSearchLoading(false);
    }
  };

  const handleClearSearch = () => {
    setSearchTerm("");
    setProducts(allProducts);
    clearSelection();
  };

  const handleCreate = () => {
    setEditingProduct(null);
    setShowForm(true);
  };

  const handleEdit = async (product: IProduct) => {
    try {
      setEditingProduct(product);
      setShowForm(true);
    } catch (error: any) {
      toast.error(error.message || "Error al cargar producto");
    }
  };

  const handleCreateProductApi = async (formData: FormData) => {
    try {
      if (editingProduct?.id) {
        await productsApi.update(editingProduct.id, formData);
        toast.success("Producto actualizado exitosamente");
      } else {
        await productsApi.create(formData);
        toast.success("Producto creado exitosamente");
      }
      setShowForm(false);
      setEditingProduct(null);

      loadProducts();
    } catch (error: any) {
      toast.error(error.message || "Error al guardar producto");
    }
  };

  const handleDelete = async (id: number) => {
    if (!confirm("¿Estás seguro de eliminar este producto?")) {
      return;
    }

    try {
      await productsApi.delete(id);
      toast.success("Producto eliminado exitosamente");
      if (selectAllMode) {
        setExcludedProductIds((prev) => prev.filter((x) => x !== id));
      } else {
        setSelectedProductIds((prev) => prev.filter((x) => x !== id));
      }
      loadProducts();
    } catch (error: any) {
      toast.error(error.message || "Error al eliminar producto");
    }
  };

  const resolveSelectedIdsForDelete = async (): Promise<number[]> => {
    if (!selectAllMode) {
      return selectedProductIds;
    }

    const allIds = await productsApi.fetchAllIds(appliedModelFilter);
    const excluded = new Set(excludedProductIds);
    return allIds.filter((id) => !excluded.has(id));
  };

  const handleDeleteSelected = async () => {
    const count = getSelectedCount();
    if (count === 0) return;
    const msg = `¿Eliminar ${count} producto${count !== 1 ? "s" : ""} seleccionado${count !== 1 ? "s" : ""}?`;
    if (!confirm(msg)) return;
    try {
      const idsToDelete = await resolveSelectedIdsForDelete();
      await Promise.all(idsToDelete.map((id) => productsApi.delete(id)));
      toast.success("Productos seleccionados eliminados");
      clearSelection();
      await loadProducts();
    } catch (error: any) {
      toast.error(error.message || "Error al eliminar productos seleccionados");
    }
  };

  const handleDeleteAll = async () => {
    if (
      !confirm(
        "¿Eliminar TODOS los productos? Esta acción no se puede deshacer."
      )
    ) {
      return;
    }

    try {
      const affected = await productsApi.deleteAll();
      toast.success(
        affected > 0
          ? `Se eliminaron ${affected} producto${affected !== 1 ? "s" : ""}`
          : "No había productos para eliminar"
      );
      setPage(1);
      clearSelection();
      await loadProducts();
    } catch (error: any) {
      toast.error(error.message || "Error al eliminar todos los productos");
    }
  };

  const handleToggleProduct = (id: number, checked: boolean) => {
    if (selectAllMode) {
      setExcludedProductIds((prev) => {
        if (checked) {
          return prev.filter((x) => x !== id);
        }
        if (prev.includes(id)) return prev;
        return [...prev, id];
      });
      return;
    }

    setSelectedProductIds((prev) => {
      if (checked) {
        if (prev.includes(id)) return prev;
        return [...prev, id];
      }
      return prev.filter((x) => x !== id);
    });
  };

  const handleToggleAllVisible = (ids: number[], checked: boolean) => {
    if (!checked) {
      clearSelection();
      return;
    }

    if (searchTerm.trim()) {
      setSelectAllMode(false);
      setExcludedProductIds([]);
      setSelectedProductIds(Array.from(new Set(ids)));
      return;
    }

    setSelectAllMode(true);
    setExcludedProductIds([]);
    setSelectedProductIds([]);
  };

  const handleCancel = () => {
    setShowForm(false);
    setEditingProduct(null);
  };

  const loadModels = async () => {
    try {
      const data = await vehiclesApi.getAllModels(true);
      setModels(data);
    } catch (error: any) {
      toast.error(error.message || "Error al cargar modelos");
    }
  };

  const handleApplyModelFilter = () => {
    setAppliedModelFilter(modelFilterDraft && modelFilterDraft > 0 ? modelFilterDraft : null);
    clearSelection();
    setSearchTerm("");
    setPage(1);
    setShowModelFilter(false);
  };

  const handleResetModelFilter = () => {
    setModelFilterDraft(null);
    setAppliedModelFilter(null);
    clearSelection();
    setSearchTerm("");
    setPage(1);
    setShowModelFilter(false);
  };

  useEffect(() => {
    loadProducts();
  }, [page, appliedModelFilter]);

  useEffect(() => {
    loadModels();
  }, []);

  const allProductsSelected =
    selectAllMode &&
    excludedProductIds.length === 0 &&
    !searchTerm.trim() &&
    !appliedModelFilter &&
    totalProductsInDb > 0;
  const selectedCount = getSelectedCount();
  const hasPartialSelection = selectedCount > 0 && !allProductsSelected;

  if (loading && products.length === 0) {
    return (
      <ProtectedRoute>
        <AdminLayout>
          <div className="text-center py-5">
            <div className="spinner-border" role="status">
              <span className="sr-only">Cargando...</span>
            </div>
          </div>
        </AdminLayout>
      </ProtectedRoute>
    );
  }

  return (
    <ProtectedRoute>
      <AdminLayout>
        <div className="page-header">
          <h1>Productos</h1>
          {!showForm && (
            <div>
              <button
                className="btn btn-outline-primary mr-2"
                onClick={() => setShowModelFilter((v) => !v)}
                type="button"
              >
                <i className="fas fa-filter" /> Filtrar por modelo
              </button>
              <button
                className="btn btn-danger mr-2"
                onClick={handleDeleteAll}
                disabled={!allProductsSelected}
              >
                <i className="fas fa-trash-alt" /> Eliminar todos
              </button>
              <button
                className="btn btn-danger mr-2"
                onClick={handleDeleteSelected}
                disabled={!hasPartialSelection}
              >
                <i className="fas fa-trash" /> Eliminar seleccionados
                {hasPartialSelection ? ` (${selectedCount})` : ""}
              </button>
              <button className="btn btn-primary" onClick={handleCreate}>
                <i className="fas fa-plus" /> Nuevo Producto
              </button>
            </div>
          )}
        </div>

        {showForm ? (
          <ProductForm
            product={editingProduct}
            handleCreateProductApi={handleCreateProductApi}
            onCancel={handleCancel}
          />
        ) : (
          <>
            {showModelFilter && (
              <div className="card mb-3">
                <div className="card-body">
                  <div className="row align-items-end">
                    <div className="col-md-8">
                      <label className="font-weight-bold mb-2">Modelo</label>
                      <select
                        className="form-control"
                        value={modelFilterDraft ?? ""}
                        onChange={(e) => {
                          const val = e.target.value;
                          setModelFilterDraft(val ? Number(val) : null);
                        }}
                      >
                        <option value="">Todos</option>
                        {models.map((m) => (
                          <option key={m.id} value={m.id}>
                            {m.name}
                          </option>
                        ))}
                      </select>
                    </div>
                    <div className="col-md-4 mt-3 mt-md-0">
                      <button type="button" className="btn btn-primary mr-2" onClick={handleApplyModelFilter}>
                        Aplicar filtro
                      </button>
                      <button type="button" className="btn btn-outline-secondary" onClick={handleResetModelFilter}>
                        Todos
                      </button>
                    </div>
                  </div>
                </div>
              </div>
            )}
            <div className="card mb-3">
              <div className="card-body">
                <div className="input-group">
                  <div className="input-group-prepend">
                    <span className="input-group-text">
                      <i className="fas fa-search" />
                    </span>
                  </div>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="Buscar por nombre o código..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    onKeyDown={(e) => e.key === "Enter" && handleSearchSubmit()}
                  />
                  <div className="input-group-append">
                    <button
                      className="btn btn-primary"
                      type="button"
                      onClick={handleSearchSubmit}
                      disabled={searchLoading}
                    >
                      {searchLoading ? (
                        <>
                          <span className="spinner-border spinner-border-sm mr-1" role="status" aria-hidden="true" />
                          Buscando...
                        </>
                      ) : (
                        <>
                          <i className="fas fa-search mr-1" />
                          Buscar
                        </>
                      )}
                    </button>
                    {searchTerm && (
                      <button
                        className="btn btn-outline-secondary"
                        type="button"
                        onClick={handleClearSearch}
                        disabled={searchLoading}
                      >
                        <i className="fas fa-times" />
                      </button>
                    )}
                  </div>
                </div>
                {searchTerm && !searchLoading && (
                  <small className="text-muted mt-2 d-block">
                    {products.length} producto{products.length !== 1 ? "s" : ""} encontrado
                    {products.length !== 1 ? "s" : ""}
                  </small>
                )}
                {appliedModelFilter && (
                  <small className="text-primary mt-1 d-block">
                    Filtro activo por modelo:{" "}
                    {models.find((m) => m.id === appliedModelFilter)?.name || `ID ${appliedModelFilter}`}
                  </small>
                )}
              </div>
            </div>
            <div className="position-relative">
              {searchLoading && (
                <div
                  className="position-absolute d-flex align-items-center justify-content-center"
                  style={{
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    backgroundColor: "rgba(255,255,255,0.85)",
                    zIndex: 10,
                    minHeight: 200,
                  }}
                >
                  <div className="text-center">
                    <div className="spinner-border text-primary mb-2" role="status">
                      <span className="sr-only">Cargando...</span>
                    </div>
                    <p className="text-muted mb-0">Cargando resultados...</p>
                  </div>
                </div>
              )}
              <ProductList
                products={products}
                onEdit={handleEdit}
                onDelete={handleDelete}
                isProductSelected={isProductSelected}
                onToggleProduct={handleToggleProduct}
                onToggleAllVisible={handleToggleAllVisible}
              />
            </div>
            {totalPages > 1 && !searchTerm && (
              <div className="pagination-container mt-4">
                <button
                  className="btn btn-sm btn-secondary"
                  disabled={page === 1}
                  onClick={() => setPage(page - 1)}
                >
                  Anterior
                </button>
                <span className="mx-3">
                  Página {page} de {totalPages}
                </span>
                <button
                  className="btn btn-sm btn-secondary"
                  disabled={page >= totalPages}
                  onClick={() => setPage(page + 1)}
                >
                  Siguiente
                </button>
              </div>
            )}
          </>
        )}
      </AdminLayout>
    </ProtectedRoute>
  );
}

export default ProductosPage;
