﻿// react
import React, { useState, useEffect } from "react";
// third-party
import { useForm } from "react-hook-form";
import { toast } from "react-toastify";
// application
import { IProduct } from "~/admin/interfaces/product";
import { vehiclesApi } from "~/admin/services/vehiclesApi";
import { IModel } from "~/admin/interfaces/vehicle";
import { InputImage, ImageItem } from "./_components/InputImage";

interface Props {
  product?: IProduct | null;
  handleCreateProductApi: (formData: FormData) => void;
  onCancel: () => void;
}

function ProductForm({ product, handleCreateProductApi, onCancel }: Props) {
  //states
  const [models, setModels] = useState<IModel[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [currentImages, setCurrentImages] = useState<string[]>(product?.images || []);
  const [pendingFiles, setPendingFiles] = useState<File[]>([]);
  const [orderedImageItems, setOrderedImageItems] = useState<ImageItem[]>([]);
  // Modo de imágenes: subida manual o enlaces web (máximo 4)
  const [imageMode, setImageMode] = useState<"upload" | "links">("upload");
  const [linkImages, setLinkImages] = useState<string[]>(["", "", "", ""]);
  const [excelLoading, setExcelLoading] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const data = await vehiclesApi.getAllModels(true);
        setModels(data);
      } catch (error) {
        console.error("Error loading models:", error);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
  } = useForm<any>({
    defaultValues: product
      ? {
          ...product,
          vehicleId: product.vehicleId,
          vehicle_brandID: product.vehicle_brandID,
          sku: product.code,
          description: product.description,
          categoria: product.categoria,
          minPrice: product.minPrice,
          offerPrice: product.offerPrice,
          maximumPrice: product.maximumPrice,
          imageUrl: undefined,
          status: product.status ?? 1,
          numberPieces: product.numberPieces,
        }
      : {
          imageUrl: undefined,
        },
  });

  const selectedVehicleId = watch("vehicleId");

  // Importa enlaces desde un Excel (columna "Imagenes")
  const handleExcelImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;
    setExcelLoading(true);
    try {
      const XLSX = await import("xlsx");
      const buffer = await file.arrayBuffer();
      const wb = XLSX.read(buffer, { type: "array" });
      const sheet = wb.Sheets[wb.SheetNames[0]];
      if (!sheet) throw new Error("Hoja vacía");
      const rows = XLSX.utils.sheet_to_json<Record<string, any>>(sheet, { defval: "" });
      if (!rows.length) throw new Error("Sin datos");

      // Busca la columna "Imagenes" (acepta acentos/caps)
      const keys = Object.keys(rows[0]);
      let colKey = keys.find((k) => k.trim().toLowerCase() === "imagenes");
      if (!colKey) colKey = keys.find((k) => k.trim().toLowerCase().includes("imagen"));
      if (!colKey) {
        toast.error('No se encontró la columna "Imagenes" en el Excel');
        return;
      }

      // Extrae hasta 4 enlaces válidos
      const links: string[] = [];
      for (const row of rows) {
        const cellVal = String(row[colKey] ?? "").trim();
        if (!cellVal) continue;
        cellVal.split(/[,;\n]+/).forEach((u) => {
          const t = u.trim();
          if (t && /^https?:\/\//i.test(t) && links.length < 4 && !links.includes(t)) {
            links.push(t);
          }
        });
        if (links.length >= 4) break;
      }

      if (!links.length) {
        toast.error("No se encontraron enlaces válidos en la columna Imagenes");
        return;
      }

      const next = ["", "", "", ""];
      links.forEach((l, i) => (next[i] = l));
      setLinkImages(next);
      toast.success(`${links.length} enlace(s) importado(s) desde el Excel`);
    } catch (error: any) {
      toast.error(error.message || "Error al leer el archivo Excel");
    } finally {
      setExcelLoading(false);
      e.target.value = "";
    }
  };

  const switchToLinksMode = () => {
    setImageMode("links");
    // Precarga los enlaces ya existentes del producto
    setLinkImages((prev) => {
      if (prev.some((v) => v.trim())) return prev;
      const cur = [...prev];
      currentImages.slice(0, 4).forEach((u, i) => {
        if (!cur[i]) cur[i] = u;
      });
      return cur;
    });
  };

  const onSubmit = (data: any) => {
    const formData = new FormData();

    formData.append("name", data.name);
    formData.append("sku", data.sku);
    formData.append("description", data.description || "");
    formData.append("categoria", data.categoria || "");
    formData.append("price", String(data.price));
    formData.append("minPrice", String(data.minPrice));
    formData.append("offerPrice", String(data.offerPrice));
    formData.append("maximumPrice", String(data.maximumPrice));
    formData.append("stock", data.stock);
    formData.append("vehicleId", String(selectedVehicleId));
    formData.append("reference", data.reference || "");
    formData.append("discount", String(data.discount || 0));
    formData.append("model", data.model);
    formData.append("number_pieces", String(data.numberPieces));
    formData.append("status", data.status ?? 1);

    if (product?.id) {
      formData.append("id", String(product.id));

      if (imageMode === "links") {
        // Modo enlaces: solo URLs externas (hasta 4)
        const validLinks = linkImages.map((l) => l.trim()).filter(Boolean).slice(0, 4);
        formData.append("existingImages", validLinks.join(","));
      } else {
        const existingUrls = currentImages.filter((url) => !url.startsWith("blob:"));
        formData.append("existingImages", existingUrls.join(","));
        if (orderedImageItems.length > 0) {
          let e = 0,
            n = 0;
          const orderParts = orderedImageItems.map((item) => {
            if (item.type === "url") return "e" + e++;
            return "n" + n++;
          });
          formData.append("imageOrder", orderParts.join(","));
        }
      }
    } else if (imageMode === "links") {
      // Crear producto con enlaces externos (hasta 4)
      const validLinks = linkImages.map((l) => l.trim()).filter(Boolean).slice(0, 4);
      formData.append("existingImages", validLinks.join(","));
    }

    if (imageMode !== "links" && pendingFiles.length > 0) {
      pendingFiles.forEach((file) => {
        formData.append("images[]", file);
      });
    }

    handleCreateProductApi(formData);
  };

  return (
    <div className="card shadow-sm">
      <div className="card-header bg-white">
        <h4 className="mb-0">
          {product ? "Editar Producto" : "Nuevo Producto"}
        </h4>
      </div>
      <div className="card-body">
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="row">
            <div className="col-md-6">
              {!loading && (
                <div className="form-group">
                  <label className="font-weight-bold">Modelo *</label>
                  <select
                    className={`form-control ${
                      errors.vehicleId ? "is-invalid" : ""
                    }`}
                    {...register("vehicleId", {
                      required: "El modelo es requerido",
                    })}
                    defaultValue={product?.vehicleId}
                  >
                    <option value="">Seleccionar modelo</option>
                    {models.map((model) => (
                      <option key={model.id} value={model.id}>
                        {model.brand_name ? `${model.brand_name} - ${model.name}` : model.name}
                      </option>
                    ))}
                  </select>
                  {errors.vehicleId && (
                    <div className="invalid-feedback">
                      {String(errors.vehicleId.message)}
                    </div>
                  )}
                </div>
              )}
            </div>
            <div className="col-md-6">
              <div className="form-group">
                <label className="font-weight-bold">Número de Piezas</label>
                <input
                  type="number"
                  placeholder="Ingrese el número de piezas"
                  className={`form-control ${
                    errors.numberPieces ? "is-invalid" : ""
                  }`}
                  {...register("numberPieces", {
                    required: "El número es requerido",
                  })}
                />
                {errors.numberPieces && (
                  <div className="invalid-feedback">
                    {String(errors.numberPieces.message)}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div className="row">
            <div className="col-md-6">
              <div className="form-group">
                <label className="font-weight-bold">Código (SKU) *</label>
                <input
                  type="text"
                  className={`form-control ${errors.sku ? "is-invalid" : ""}`}
                  {...register("sku", { required: "El código es requerido" })}
                />
                {errors.sku && (
                  <div className="invalid-feedback">{String(errors.sku.message)}</div>
                )}
              </div>
            </div>
            <div className="col-md-6">
              <div className="form-group">
                <label className="font-weight-bold">Referencia</label>
                <input
                  type="text"
                  className="form-control"
                  {...register("reference")}
                />
              </div>
            </div>
          </div>

          <div className="row">
            <div className="col-md-6">
              <div className="form-group">
                <label className="font-weight-bold">
                  Nombre del Producto *
                </label>
                <input
                  type="text"
                  className={`form-control ${errors.name ? "is-invalid" : ""}`}
                  {...register("name", { required: "El nombre es requerido" })}
                />
                {errors.name && (
                  <div className="invalid-feedback">{String(errors.name.message)}</div>
                )}
              </div>
            </div>
            <div className="col-md-6">
              <div className="form-group">
                <label className="font-weight-bold">Modelo específico *</label>
                <input
                  type="text"
                  className={`form-control ${errors.model ? "is-invalid" : ""}`}
                  {...register("model", { required: "El modelo es requerido" })}
                />
                {errors.model && (
                  <div className="invalid-feedback">{String(errors.model.message)}</div>
                )}
              </div>
            </div>
          </div>

          <div className="form-group">
            <label className="font-weight-bold">Descripción</label>
            <textarea
              className="form-control"
              rows={3}
              {...register("description")}
            />
          </div>

<div className="form-group">
            <label className="font-weight-bold">Categoría</label>
            <input
              type="text"
              className="form-control"
              placeholder="Ej: Frenos, Suspensión, Filtros..."
              {...register("categoria")}
            />
            <small className="text-muted">
              <i className="fas fa-info-circle mr-1" />
              La categoría se usa para mostrar productos relacionados en el carrusel del sitio web.
            </small>
          </div>

          {/* Prices */}
          {/* Prices */}
          <div className="row">
            <div className="col-md-4">
              <div className="form-group">
                <label className="font-weight-bold">
                  Precio Mínimo - Mayor *
                </label>
                <div className="input-group">
                  <div className="input-group-prepend">
                    <span className="input-group-text">$</span>
                  </div>
                  <input
                    type="number"
                    step="0.01"
                    className={`form-control ${
                      errors.minPrice ? "is-invalid" : ""
                    }`}
                    {...register("minPrice", {
                      required: "Requerido",
                      min: 0,
                      valueAsNumber: true,
                    })}
                  />
                </div>
              </div>
            </div>

            <div className="col-md-4">
              <div className="form-group">
                <label className="font-weight-bold">Precio Oferta *</label>
                <div className="input-group">
                  <div className="input-group-prepend">
                    <span className="input-group-text">$</span>
                  </div>
                  <input
                    type="number"
                    step="0.01"
                    className={`form-control ${
                      errors.offerPrice ? "is-invalid" : ""
                    }`}
                    {...register("offerPrice", {
                      required: "Requerido",
                      min: 0,
                      valueAsNumber: true,
                    })}
                  />
                </div>
              </div>
            </div>

            <div className="col-md-4">
              <div className="form-group">
                <label className="font-weight-bold">Precio Máximo *</label>
                <div className="input-group">
                  <div className="input-group-prepend">
                    <span className="input-group-text">$</span>
                  </div>
                  <input
                    type="number"
                    step="0.01"
                    className={`form-control ${
                      errors.maximumPrice ? "is-invalid" : ""
                    }`}
                    {...register("maximumPrice", {
                      required: "Requerido",
                      min: 0,
                      valueAsNumber: true,
                    })}
                  />
                </div>
              </div>
            </div>
          </div>

          {/* Status */}
          <div className="form-group">
            <label className="font-weight-bold">Estado *</label>
            <select
              className={`form-control ${errors.status ? "is-invalid" : ""}`}
              {...register("status", { required: "El estado es requerido" })}
            >
              <option value="" selected disabled>
                Seleccionar estado
              </option>
              <option value="1">Activo</option>
              <option value="0">Inactivo</option>
            </select>
            {errors.status && (
              <div className="invalid-feedback">{String(errors.status.message)}</div>
            )}
          </div>

          <hr />

          {/* Imágenes: subida manual o enlaces web */}
          <div className="form-group">
            <label className="font-weight-bold">Imágenes (máximo 4)</label>
            <div className="d-flex mb-3">
              <button
                type="button"
                className={`btn btn-sm mr-2 ${imageMode === "upload" ? "btn-primary" : "btn-outline-primary"}`}
                onClick={() => setImageMode("upload")}
              >
                <i className="fas fa-upload mr-1" /> Subir archivos
              </button>
              <button
                type="button"
                className={`btn btn-sm ${imageMode === "links" ? "btn-primary" : "btn-outline-primary"}`}
                onClick={switchToLinksMode}
              >
                <i className="fas fa-link mr-1" /> Enlaces web
              </button>
            </div>

            {imageMode === "upload" ? (
              <InputImage
                register={register}
                initialImages={product?.images}
                onImagesChange={(imgs) => setCurrentImages(imgs)}
                onFilesChange={(files) => setPendingFiles(files)}
                onOrderedChange={(items) => setOrderedImageItems(items)}
              />
            ) : (
              <div className="border rounded p-3 bg-light">
                <div className="d-flex align-items-center justify-content-between mb-2 flex-wrap">
                  <small className="text-muted">
                    Pega hasta 4 enlaces de imágenes de otra página web:
                  </small>
                  <label
                    className="btn btn-outline-success btn-sm mb-0"
                    style={{ cursor: "pointer", pointerEvents: excelLoading ? "none" : "auto" }}
                  >
                    {excelLoading ? (
                      <>
                        <span className="spinner-border spinner-border-sm mr-1" role="status" aria-hidden="true" />
                        Leyendo...
                      </>
                    ) : (
                      <>
                        <i className="fas fa-file-excel mr-1" /> Importar desde Excel
                      </>
                    )}
                    <input type="file" accept=".xlsx,.xls" hidden onChange={handleExcelImport} />
                  </label>
                </div>
                {[0, 1, 2, 3].map((i) => (
                  <div className="d-flex align-items-center mb-2" key={i}>
                    <span className="mr-2 text-muted font-weight-bold">{i + 1}.</span>
                    <input
                      type="url"
                      className="form-control form-control-sm"
                      placeholder={`https://enlace-de-imagen-${i + 1}.jpg`}
                      value={linkImages[i]}
                      onChange={(e) =>
                        setLinkImages((prev) =>
                          prev.map((v, idx) => (idx === i ? e.target.value : v))
                        )
                      }
                    />
                    {linkImages[i] && (
                      <img
                        src={linkImages[i]}
                        alt={`Vista previa ${i + 1}`}
                        className="ml-2 rounded border bg-white"
                        style={{ width: 40, height: 40, objectFit: "cover", flexShrink: 0 }}
                        onError={(ev) => {
                          (ev.target as HTMLImageElement).style.opacity = "0.25";
                        }}
                        onLoad={(ev) => {
                          (ev.target as HTMLImageElement).style.opacity = "1";
                        }}
                      />
                    )}
                  </div>
                ))}
                <small className="text-muted">
                  <i className="fas fa-info-circle mr-1" />
                  El Excel debe tener una columna llamada <strong>Imagenes</strong> con los enlaces
                  (pueden ir varios separados por coma).
                </small>
              </div>
            )}
          </div>

          <hr />

          <div className="d-flex justify-content-end mt-4">
            <button
              type="button"
              className="btn btn-outline-secondary mr-2"
              onClick={onCancel}
            >
              Cancelar
            </button>
            <button type="submit" className="btn btn-primary px-4">
              <i className="fas fa-save mr-2" />{" "}
              {product ? "Actualizar" : "Guardar Producto"}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default ProductForm;
