"use client";

import type { InputHTMLAttributes } from "react";
import { Plus, Trash2, Scissors } from "lucide-react";
import Button from "@/components/ui/Button";
import { cn } from "@/lib/cn";
import { emptyCorteDraft } from "@/lib/cortes/drafts";
import { MAT_GROUPS, getMatGroup, matHasCanto } from "@/lib/cortes/materials";
import type { CorteItemDraft, CorteVeta } from "@/lib/cortes/types";

interface Props {
  items: CorteItemDraft[];
  onChange: (items: CorteItemDraft[]) => void;
  compact?: boolean;
  allowAdd?: boolean;
  allowRemove?: boolean;
}

const VETA_OPTIONS: { value: CorteVeta; label: string }[] = [
  { value: "ninguna", label: "Libre" },
  { value: "ancho", label: "A" },
  { value: "alto", label: "B" },
];

export default function CortesEditor({ items, onChange, allowAdd = true, allowRemove = true }: Props) {
  function addItem() {
    onChange([...items, emptyCorteDraft(items.length)]);
  }

  function updateItem(index: number, patch: Partial<CorteItemDraft>) {
    onChange(items.map((item, i) => (i === index ? normalizeItemPatch(item, patch) : item)));
  }

  function removeItem(index: number) {
    onChange(items.filter((_, i) => i !== index).map((item, i) => ({ ...item, sort_order: i })));
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between gap-3">
        <div>
          <h2 className="flex items-center gap-2 font-bold text-ink">
            <Scissors size={16} /> Cortes
          </h2>
          <p className="mt-0.5 text-xs text-faint">
            Lista de produccion para taller.
          </p>
        </div>
        {allowAdd && (
          <Button type="button" variant="secondary" size="sm" className="h-8 rounded-lg px-2 text-xs" onClick={addItem}>
            <Plus size={14} /> Linea
          </Button>
        )}
      </div>

      {items.length === 0 ? (
        <button
          type="button"
          onClick={addItem}
          className="w-full rounded-lg border border-dashed border-line bg-canvas px-3 py-5 text-sm text-faint hover:border-line-strong hover:text-ink"
        >
          Agregar cortes manuales para reemplazar el cuaderno.
        </button>
      ) : (
        <div className="overflow-x-auto rounded-lg border border-line bg-surface">
          <div className="min-w-[600px]">
            <div className="grid grid-cols-[42px_66px_66px_minmax(104px,1.4fr)_minmax(70px,0.9fr)_46px_46px_54px_minmax(120px,1.7fr)_30px] gap-1 border-b border-line bg-canvas/70 px-2 py-1.5 text-[11px] font-bold uppercase text-faint">
              <span>Cant.</span>
              <span>Ancho</span>
              <span>Alto</span>
              <span>Material</span>
              <span>Color</span>
              <span>Cto A</span>
              <span>Cto B</span>
              <span>Veta</span>
              <span>Nota</span>
              <span />
            </div>
            {items.map((item, index) => {
              const group = getMatGroup(item.material);
              const hasCanto = matHasCanto(item.material);
              return (
                <div
                  key={index}
                  onKeyDown={(e) => {
                    if (e.key === "Enter" && e.shiftKey && allowAdd) {
                      e.preventDefault();
                      addItem();
                    }
                  }}
                  className="grid grid-cols-[42px_66px_66px_minmax(104px,1.4fr)_minmax(70px,0.9fr)_46px_46px_54px_minmax(120px,1.7fr)_30px] gap-1 border-b border-line px-2 py-1.5 last:border-b-0"
                >
                  <TinyInput
                    type="number"
                    min="1"
                    inputMode="numeric"
                    value={String(item.cantidad || "")}
                    onChange={(e) => updateItem(index, { cantidad: Number(e.target.value) || 1 })}
                  />
                  <TinyInput
                    type="number"
                    min="0"
                    inputMode="numeric"
                    value={String(item.ancho || "")}
                    onChange={(e) => updateItem(index, { ancho: Number(e.target.value) || 0 })}
                  />
                  {group?.isNota ? (
                    <div />
                  ) : (
                    <TinyInput
                      type="number"
                      min="0"
                      inputMode="numeric"
                      value={String(item.alto || "")}
                      onChange={(e) => updateItem(index, { alto: Number(e.target.value) || 0 })}
                    />
                  )}
                  <select
                    value={item.material}
                    onChange={(e) => updateItem(index, { material: e.target.value })}
                    className="h-8 w-full rounded-md border border-line bg-surface px-2 text-xs text-ink outline-none focus:border-brand"
                  >
                    {MAT_GROUPS.map((matGroup) => (
                      <optgroup key={matGroup.family} label={matGroup.label}>
                        {matGroup.codes.map((code) => (
                          <option key={code} value={code}>
                            {code}
                          </option>
                        ))}
                      </optgroup>
                    ))}
                  </select>
                  {group?.family === "melamina-color" ? (
                    <TinyInput
                      placeholder="Color"
                      value={item.color || ""}
                      onChange={(e) => updateItem(index, { color: e.target.value })}
                    />
                  ) : (
                    <div />
                  )}
                  {hasCanto ? (
                    <CantoRotaryInput value={item.canto_ancho || 0} onChange={(value) => updateItem(index, { canto_ancho: value })} />
                  ) : (
                    <div />
                  )}
                  {hasCanto ? (
                    <CantoRotaryInput value={item.canto_alto || 0} onChange={(value) => updateItem(index, { canto_alto: value })} />
                  ) : (
                    <div />
                  )}
                  {hasCanto ? (
                    <VetaRotaryInput value={item.veta || "ninguna"} onChange={(value) => updateItem(index, { veta: value })} />
                  ) : (
                    <div />
                  )}
                  <textarea
                    value={item.nota || ""}
                    onChange={(e) => updateItem(index, { nota: e.target.value })}
                    onKeyDown={(e) => {
                      if (e.key === "Enter" && e.shiftKey) {
                        e.preventDefault();
                        e.stopPropagation();
                        if (allowAdd) addItem();
                      }
                    }}
                    rows={1}
                    placeholder="Nota"
                    className="min-h-8 w-full rounded-md border border-line bg-surface px-2 py-1 text-xs text-ink outline-none resize-y focus:border-brand"
                  />
                  {allowRemove ? (
                    <button
                      type="button"
                      onClick={() => removeItem(index)}
                      className="inline-flex h-8 w-8 items-center justify-center rounded-md text-faint hover:bg-red-50 hover:text-bad"
                      title="Quitar corte"
                    >
                      <Trash2 size={14} />
                    </button>
                  ) : (
                    <div />
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}

function TinyInput(props: InputHTMLAttributes<HTMLInputElement>) {
  return (
    <input
      {...props}
      className={cn(
        "h-8 w-full rounded-md border border-line bg-surface px-2 text-xs text-ink outline-none focus:border-brand",
        props.className,
      )}
    />
  );
}

function CantoRotaryInput({ value, onChange }: { value: number; onChange: (value: number) => void }) {
  function cycle() {
    onChange((value + 1) % 3);
  }
  return (
    <button
      type="button"
      onClick={cycle}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          cycle();
        }
      }}
      className="h-8 w-full rounded-md border border-line bg-surface text-xs font-bold text-ink outline-none hover:border-brand-dark focus:border-brand focus:ring-1 focus:ring-brand flex items-center justify-center transition-colors"
    >
      {value}
    </button>
  );
}

const VETA_ROTATION: { value: CorteVeta; label: string }[] = [
  { value: "ninguna", label: "Sin" },
  { value: "ancho", label: "A" },
  { value: "alto", label: "B" },
];

function VetaRotaryInput({ value, onChange }: { value: CorteVeta; onChange: (value: CorteVeta) => void }) {
  const currentIndex = VETA_ROTATION.findIndex((opt) => opt.value === value);
  const currentOpt = VETA_ROTATION[currentIndex >= 0 ? currentIndex : 0];

  function cycle() {
    const nextIndex = (currentIndex + 1) % VETA_ROTATION.length;
    onChange(VETA_ROTATION[nextIndex].value);
  }

  return (
    <button
      type="button"
      onClick={cycle}
      onKeyDown={(e) => {
        if (e.key === "Enter" || e.key === " ") {
          e.preventDefault();
          cycle();
        }
      }}
      className={cn(
        "h-8 w-full rounded-md border text-xs font-semibold outline-none hover:border-brand-dark focus:border-brand focus:ring-1 focus:ring-brand flex items-center justify-center transition-colors",
        value !== "ninguna"
          ? "border-brand-soft bg-brand-soft text-brand-dark font-bold"
          : "border-line bg-surface text-ink-soft"
      )}
    >
      {currentOpt.label}
    </button>
  );
}

function normalizeItemPatch(item: CorteItemDraft, patch: Partial<CorteItemDraft>): CorteItemDraft {
  const next = { ...item, ...patch };
  const group = getMatGroup(next.material);
  if (!group?.hasCanto) {
    next.canto_ancho = 0;
    next.canto_alto = 0;
    next.canto_ancho_hecho = 0;
    next.canto_alto_hecho = 0;
    next.veta = "ninguna";
  }
  if (group?.family === "notas" || group?.family === "herrajes") {
    next.ancho = 0;
    next.alto = 0;
  } else if (group?.family === "pino") {
    next.alto = 0;
  }
  if (group?.family !== "melamina-color") {
    next.color = "";
  }
  return next;
}
