import { Plus, Trash2, Upload } from "lucide-react";
import {
  useFieldArray,
  type FieldArrayPath,
  type UseFormReturn,
} from "react-hook-form";
import type { ApiProductUnit } from "@/lib/api/types";
import { type ProductFormValues } from "./product.schema";
import { Field, SectionCard, UnitSelect, inputClass } from "./fields";
import WeightCalculator from "./WeightCalculator";

type Props = { form: UseFormReturn<ProductFormValues>; units: ApiProductUnit[] };

type SpecName = Extract<FieldArrayPath<ProductFormValues>, "physical_specs" | "chemical_specs">;

function SpecTable({
  form,
  name,
  title,
}: {
  form: UseFormReturn<ProductFormValues>;
  name: SpecName;
  title: string;
}) {
  const {
    register,
    control,
    watch,
    setValue,
    formState: { errors },
  } = form;
  const { fields, append, remove } = useFieldArray({ control, name });
  const rowErrors = errors[name] as Array<{ parameter?: { message?: string }; value?: { message?: string } }> | undefined;

  return (
    <SectionCard title={title} subtitle="Add specification details">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[560px] border-collapse text-sm">
          <thead>
            <tr className="text-left text-xs font-medium text-gray-600">
              <th className="pb-2 pr-3">Parameter *</th>
              <th className="pb-2 pr-3">Value *</th>
              <th className="pb-2 pr-3">Image</th>
              <th className="pb-2 text-right">Action</th>
            </tr>
          </thead>
          <tbody>
            {fields.map((field, i) => {
              const image = watch(`${name}.${i}.image`) as File | null;
              const inputId = `${name}-img-${i}`;
              return (
                <tr key={field.id} className="align-top">
                  <td className="py-1.5 pr-3">
                    <input
                      {...register(`${name}.${i}.parameter`)}
                      className={inputClass}
                      placeholder="Enter parameter"
                    />
                    {rowErrors?.[i]?.parameter?.message ? (
                      <p className="mt-1 text-xs text-red-600">{rowErrors[i]?.parameter?.message}</p>
                    ) : null}
                  </td>
                  <td className="py-1.5 pr-3">
                    <input {...register(`${name}.${i}.value`)} className={inputClass} placeholder="Enter value" />
                    {rowErrors?.[i]?.value?.message ? (
                      <p className="mt-1 text-xs text-red-600">{rowErrors[i]?.value?.message}</p>
                    ) : null}
                  </td>
                  <td className="py-1.5 pr-3">
                    <label
                      htmlFor={inputId}
                      title={image ? image.name : "Upload image"}
                      className="inline-flex h-[38px] w-full max-w-[120px] cursor-pointer items-center justify-center gap-1.5 rounded-lg border border-gray-200 px-2 text-xs text-gray-600 hover:border-[#CC1414]"
                    >
                      <Upload className="h-4 w-4" />
                      <span className="truncate">{image ? image.name : "Upload"}</span>
                    </label>
                    <input
                      id={inputId}
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(e) => {
                        const file = e.target.files?.[0] ?? null;
                        setValue(`${name}.${i}.image`, file, { shouldDirty: true });
                      }}
                    />
                  </td>
                  <td className="py-1.5 text-right">
                    <button
                      type="button"
                      onClick={() => remove(i)}
                      disabled={fields.length === 1}
                      className="rounded-md p-2 text-[#CC1414] hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-40"
                      aria-label="Remove specification"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      <div className="mt-3 flex flex-wrap items-center gap-3">
        <button
          type="button"
          onClick={() => append({ parameter: "", value: "", image: null })}
          className="inline-flex items-center gap-1.5 rounded-lg border border-[#CC1414] px-3 py-1.5 text-sm font-medium text-[#CC1414] hover:bg-rose-50"
        >
          <Plus className="h-4 w-4" /> Add Specification
        </button>
        <span className="text-xs text-gray-500">You can upload image for reference (JPG, PNG - Max 5MB)</span>
      </div>
    </SectionCard>
  );
}

export default function Step4Specs({ form, units }: Props) {
  const {
    register,
    watch,
    setValue,
    formState: { errors },
  } = form;

  return (
    <div className="space-y-4">
      <SpecTable form={form} name="physical_specs" title="Physical Specifications" />
      <SpecTable form={form} name="chemical_specs" title="Chemical Specifications" />

      <SectionCard title="Weight / Quantity">
        <div className="mb-4">
          <WeightCalculator
            units={units}
            onUse={(value, unit) => {
              setValue("net_weight", value, { shouldValidate: true, shouldDirty: true });
              setValue("weight_unit", unit, { shouldValidate: true, shouldDirty: true });
            }}
          />
        </div>
        <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
          <Field label="Unit" required error={errors.weight_unit?.message}>
            <UnitSelect
              units={units}
              current={watch("weight_unit")}
              placeholder="Select unit (e.g. Kg, MT)"
              {...register("weight_unit")}
            />
          </Field>

          <Field label="Net Weight / Quantity" required error={errors.net_weight?.message}>
            <input {...register("net_weight")} className={inputClass} placeholder="e.g. 0.889" inputMode="decimal" />
          </Field>

          <Field label="Weight tolerance (± %)" error={errors.tolerance?.message}>
            <input {...register("tolerance")} className={inputClass} placeholder="± % e.g. 2.5" inputMode="decimal" />
          </Field>
        </div>
      </SectionCard>
    </div>
  );
}
