import { Info, Plus, Trash2 } from "lucide-react";
import { useFieldArray, type UseFormReturn } from "react-hook-form";
import { isKnownCharge, knownChargeTypes, type ProductFormValues } from "./product.schema";
import { Field, SectionCard, inputClass } from "./fields";

type Props = { form: UseFormReturn<ProductFormValues> };

const unitOf = (type: string) =>
  knownChargeTypes.find((charge) => charge.type.toLowerCase() === type.toLowerCase())?.unit ?? "₹";

const hintOf = (type: string) =>
  knownChargeTypes.find((charge) => charge.type.toLowerCase() === type.toLowerCase())?.hint ?? "";

export default function Step7ChargesStatus({ form }: Props) {
  const {
    register,
    control,
    watch,
    formState: { errors },
  } = form;
  const { fields, append, remove } = useFieldArray({ control, name: "charges" });
  const rows = watch("charges");

  return (
    <div className="space-y-4">
      <SectionCard title="Other Charges" subtitle="To calculate Ex-Price">
        <div className="space-y-2">
          {fields.map((field, index) => {
            const type = rows?.[index]?.type ?? "";
            const known = isKnownCharge(type);
            const enabled = rows?.[index]?.enabled ?? false;

            return (
              <div
                key={field.id}
                className={`rounded-lg border p-3 ${enabled ? "border-[#CC1414] bg-rose-50/40" : "border-gray-200"}`}
              >
                <div className="flex flex-wrap items-center gap-3">
                  <label className="flex min-w-[160px] flex-1 items-center gap-2 text-sm font-medium text-gray-800">
                    <input
                      type="checkbox"
                      {...register(`charges.${index}.enabled`)}
                      className="h-4 w-4 flex-shrink-0 accent-[#CC1414]"
                    />
                    {known ? (
                      <span>{type}</span>
                    ) : (
                      <input
                        {...register(`charges.${index}.type`)}
                        className={inputClass}
                        placeholder="Charge name"
                      />
                    )}
                  </label>

                  {/* Extra charges can pull the ex price down as well as up —
                      without an operator the API ignores the amount entirely. */}
                  {known ? null : (
                    <select
                      {...register(`charges.${index}.operator`)}
                      className="w-16 rounded-lg border border-gray-200 px-2 py-2 text-sm focus:border-[#CC1414] focus:outline-none"
                      aria-label="Add to or subtract from the ex price"
                    >
                      <option value="+">+</option>
                      <option value="-">−</option>
                    </select>
                  )}

                  <div className="relative w-36">
                    <input
                      {...register(`charges.${index}.amount`)}
                      className={`${inputClass} pr-8`}
                      placeholder="0"
                      inputMode="decimal"
                      disabled={!enabled}
                    />
                    <span className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-xs text-gray-400">
                      {unitOf(type)}
                    </span>
                  </div>

                  {known ? (
                    <span className="w-9" />
                  ) : (
                    <button
                      type="button"
                      onClick={() => remove(index)}
                      className="rounded-md p-2 text-[#CC1414] hover:bg-rose-100"
                      aria-label="Remove charge"
                    >
                      <Trash2 className="h-4 w-4" />
                    </button>
                  )}
                </div>

                {known && hintOf(type) ? (
                  <p className="mt-1 pl-6 text-xs text-gray-500">{hintOf(type)}</p>
                ) : null}
              </div>
            );
          })}
        </div>

        <button
          type="button"
          onClick={() => append({ type: "", enabled: true, amount: "", operator: "+" })}
          className="mt-3 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 Charge
        </button>
      </SectionCard>

      <SectionCard title="Publishing" subtitle="Product goes live only after admin approval">
        <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
          <Field label="Publish On" error={errors.publish_on?.message}>
            <input type="date" {...register("publish_on")} className={inputClass} />
          </Field>
        </div>
      </SectionCard>

      <div className="flex items-start gap-2 rounded-xl border border-rose-100 bg-rose-50/70 p-4 text-sm text-gray-700">
        <Info className="mt-0.5 h-4 w-4 flex-shrink-0 text-[#CC1414]" />
        <div>
          <p className="font-medium text-gray-800">
            Ex-Price will be calculated automatically based on Size Variant Price
          </p>
          <p className="mt-0.5 text-xs text-gray-600">
            Ex-Price = Base Price + Gauge Difference + Loading + Insurance + Quality Inspection +
            Other Charges, plus GST on the total.
          </p>
        </div>
      </div>
    </div>
  );
}
