"use client";

import { useReducer, useTransition, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { createHarvestLot } from "@/actions/route-trace/lots";

type Props = {
  isOpen: boolean;
  onClose: () => void;
  brandId: string;
};

// ── State + Reducer ──────────────────────────────────────────────────────────
type State = {
  error: string | null;
  notesOpen: boolean;
  crop_type: string;
  variety: string;
  harvest_date: string;
  field_location: string;
  field_block: string;
  worker_name: string;
  packer_name: string;
  quantity_lbs: string;
  yield_estimate_lbs: string;
  yield_unit: string;
  customYieldUnit: string;
  bin_id: string;
  container_id: string;
  pallets: string;
  notes: string;
};

type Action =
  | { type: "SET_FIELD"; field: keyof State; value: string }
  | { type: "SET_ERROR"; error: string | null }
  | { type: "TOGGLE_NOTES" }
  | { type: "RESET" };

function todayIso(): string {
  return new Date().toISOString().split("T")[0];
}

function makeInitialState(): State {
  return {
    error: null,
    notesOpen: false,
    crop_type: "",
    variety: "",
    harvest_date: todayIso(),
    field_location: "",
    field_block: "",
    worker_name: "",
    packer_name: "",
    quantity_lbs: "",
    yield_estimate_lbs: "",
    yield_unit: "lbs",
    customYieldUnit: "",
    bin_id: "",
    container_id: "",
    pallets: "",
    notes: "",
  };
}

const initialState: State = makeInitialState();

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_FIELD":
      return { ...state, [action.field]: action.value };
    case "SET_ERROR":
      return { ...state, error: action.error };
    case "TOGGLE_NOTES":
      return { ...state, notesOpen: !state.notesOpen };
    case "RESET":
      return makeInitialState();
  }
}

// ── Subcomponent: ModalHeader ───────────────────────────────────────────────
function ModalHeader({ onClose }: { onClose: () => void }) {
  return (
    <div
      className="sticky top-0 border-b px-6 py-5 flex items-center justify-between"
      style={{ backgroundColor: "white", borderColor: "var(--admin-border)" }}
    >
      <div className="flex items-center gap-3">
        <div
          className="flex h-9 w-9 items-center justify-center rounded-xl"
          style={{ backgroundColor: "var(--admin-accent-light)" }}
        >
          <svg
            className="h-5 w-5"
            style={{ color: "var(--admin-accent)" }}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth="2"
          >
            <path d="M12 22V12M12 12C12 12 7 10 7 5c0-2.5 2.5-5 5-5s5 2.5 5 5c0 5-5 7-5 7z" />
          </svg>
        </div>
        <div>
          <h2 className="text-lg font-bold" style={{ color: "var(--admin-text-primary)" }}>
            New Harvest Lot
          </h2>
          <p className="text-sm" style={{ color: "var(--admin-text-muted)" }}>
            Quick entry — scan or fill in the fields below
          </p>
        </div>
      </div>
      <button
        type="button"
        aria-label="Close"
        onClick={onClose}
        className="flex h-9 w-9 items-center justify-center rounded-xl border transition-colors hover:bg-stone-50"
        style={{ borderColor: "var(--admin-border)" }}
      >
        <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2">
          <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
    </div>
  );
}

// ── Subcomponent: ErrorBanner ───────────────────────────────────────────────
function ErrorBanner({ message }: { message: string }) {
  return (
    <div
      className="rounded-xl p-4 text-sm border"
      style={{
        backgroundColor: "rgba(239, 68, 68, 0.1)",
        borderColor: "rgba(239, 68, 68, 0.3)",
        color: "rgb(239, 68, 68)",
      }}
    >
      {message}
    </div>
  );
}

// ── Subcomponent: RequiredFieldsSection ─────────────────────────────────────
type RequiredFieldsProps = {
  cropType: string;
  variety: string;
  harvestDate: string;
  onSet: (field: "crop_type" | "variety" | "harvest_date", value: string) => void;
};

function RequiredFieldsSection({ cropType, variety, harvestDate, onSet }: RequiredFieldsProps) {
  return (
    <>
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label
            htmlFor="fld-1-crop-type"
            className="block text-sm font-semibold mb-2"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Crop Type *
          </label>
          <input
            id="fld-1-crop-type"
            aria-label=". Sweet Corn"
            type="text"
            value={cropType}
            onChange={(e) => onSet("crop_type", e.target.value)}
            placeholder="e.g. Sweet Corn"
            required
            className="w-full rounded-xl border px-4 py-4 text-lg font-medium outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
        <div>
          <label
            htmlFor="fld-2-variety"
            className="block text-sm font-semibold mb-2"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Variety
          </label>
          <input
            id="fld-2-variety"
            aria-label=". Golden Bantam"
            type="text"
            value={variety}
            onChange={(e) => onSet("variety", e.target.value)}
            placeholder="e.g. Golden Bantam"
            className="w-full rounded-xl border px-4 py-4 text-lg font-medium outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
      </div>
      <div>
        <label
          htmlFor="fld-3-harvest-date"
          className="block text-sm font-semibold mb-2"
          style={{ color: "var(--admin-text-primary)" }}
        >
          Harvest Date *
        </label>
        <input
          id="fld-3-harvest-date"
          aria-label="Date"
          type="date"
          value={harvestDate}
          onChange={(e) => onSet("harvest_date", e.target.value)}
          required
          className="w-full rounded-xl border px-4 py-4 text-lg font-medium outline-none transition-colors"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-bg-subtle)",
            color: "var(--admin-text-primary)",
          }}
        />
      </div>
    </>
  );
}

// ── Subcomponent: FieldLocationSection ──────────────────────────────────────
type FieldLocationProps = {
  fieldLocation: string;
  fieldBlock: string;
  workerName: string;
  onSet: (field: "field_location" | "field_block" | "worker_name", value: string) => void;
};

function FieldLocationSection({
  fieldLocation,
  fieldBlock,
  workerName,
  onSet,
}: FieldLocationProps) {
  return (
    <div className="border-t pt-5" style={{ borderColor: "var(--admin-border)" }}>
      <p
        className="text-xs font-semibold uppercase tracking-wider mb-3"
        style={{ color: "var(--admin-text-muted)" }}
      >
        Field &amp; Location
      </p>
      <div className="space-y-3">
        <div>
          <label
            htmlFor="fld-4-field-location"
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Field / Location *
          </label>
          <input
            id="fld-4-field-location"
            aria-label=". North Field"
            type="text"
            value={fieldLocation}
            onChange={(e) => onSet("field_location", e.target.value)}
            placeholder="e.g. North Field"
            required
            className="w-full rounded-xl border px-4 py-3.5 text-base outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
        <div className="grid grid-cols-2 gap-3">
          <div>
            <label
              htmlFor="fld-5-field-block"
              className="block text-xs font-medium mb-1.5"
              style={{ color: "var(--admin-text-primary)" }}
            >
              Field Block
            </label>
            <input
              id="fld-5-field-block"
              aria-label=". Block A"
              type="text"
              value={fieldBlock}
              onChange={(e) => onSet("field_block", e.target.value)}
              placeholder="e.g. Block A"
              className="w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors"
              style={{
                borderColor: "var(--admin-border)",
                backgroundColor: "var(--admin-bg-subtle)",
                color: "var(--admin-text-primary)",
              }}
            />
          </div>
          <div>
            <label
              htmlFor="fld-6-worker-harvest-lead"
              className="block text-xs font-medium mb-1.5"
              style={{ color: "var(--admin-text-primary)" }}
            >
              Worker / Harvest Lead
            </label>
            <input
              id="fld-6-worker-harvest-lead"
              aria-label=". Maria S."
              type="text"
              value={workerName}
              onChange={(e) => onSet("worker_name", e.target.value)}
              placeholder="e.g. Maria S."
              className="w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors"
              style={{
                borderColor: "var(--admin-border)",
                backgroundColor: "var(--admin-bg-subtle)",
                color: "var(--admin-text-primary)",
              }}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

// ── Subcomponent: WeightYieldSection ────────────────────────────────────────
type WeightYieldProps = {
  quantityLbs: string;
  yieldEstimateLbs: string;
  yieldUnit: string;
  customYieldUnit: string;
  onSet: (
    field: "quantity_lbs" | "yield_estimate_lbs" | "yield_unit" | "customYieldUnit",
    value: string,
  ) => void;
};

function WeightYieldSection({
  quantityLbs,
  yieldEstimateLbs,
  yieldUnit,
  customYieldUnit,
  onSet,
}: WeightYieldProps) {
  return (
    <div className="border-t pt-5" style={{ borderColor: "var(--admin-border)" }}>
      <p
        className="text-xs font-semibold uppercase tracking-wider mb-3"
        style={{ color: "var(--admin-text-muted)" }}
      >
        Weight &amp; Yield
      </p>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label
            htmlFor="fld-7-actual-qty"
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Actual Qty
          </label>
          <input
            id="fld-7-actual-qty"
            aria-label=". 4800"
            type="number"
            value={quantityLbs}
            onChange={(e) => onSet("quantity_lbs", e.target.value)}
            placeholder="e.g. 4800"
            min="0"
            step="0.01"
            className="w-full rounded-xl border px-3 py-3.5 text-base outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
        <div>
          <label
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
            htmlFor="fld-yield-est"
          >
            Yield Est.
          </label>
          <div
            className="flex rounded-xl border overflow-hidden transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
            }}
          >
            <input
              id="fld-yield-est"
              aria-label=". 5000"
              type="number"
              value={yieldEstimateLbs}
              onChange={(e) => onSet("yield_estimate_lbs", e.target.value)}
              placeholder="e.g. 5000"
              min="0"
              step="0.01"
              className="flex-1 px-3 py-3.5 text-base outline-none bg-transparent"
              style={{ color: "var(--admin-text-primary)" }}
            />
            <select
              aria-label="Select"
              value={yieldUnit}
              onChange={(e) => onSet("yield_unit", e.target.value)}
              className="px-2 py-3.5 text-sm font-semibold outline-none border-l cursor-pointer"
              style={{
                borderColor: "var(--admin-border)",
                backgroundColor: "var(--admin-bg)",
                color: "var(--admin-text-muted)",
              }}
            >
              <option value="lbs">lbs</option>
              <option value="bushel">bu</option>
              <option value="box">bx</option>
              <option value="sack">sk</option>
              <option value="crate">cr</option>
              <option value="bin">bn</option>
              <option value="pallet">plt</option>
              <option value="custom">custom</option>
            </select>
          </div>
          {yieldUnit === "custom" && (
            <input
              aria-label="Unit Name…"
              type="text"
              placeholder="Unit name…"
              value={customYieldUnit}
              onChange={(e) => onSet("customYieldUnit", e.target.value)}
              className="mt-1.5 w-full rounded-xl border px-3 py-2 text-sm outline-none transition-colors"
              style={{
                borderColor: "var(--admin-border)",
                backgroundColor: "var(--admin-bg-subtle)",
                color: "var(--admin-text-primary)",
              }}
            />
          )}
        </div>
      </div>
    </div>
  );
}

// ── Subcomponent: BinContainerSection ───────────────────────────────────────
type BinContainerProps = {
  binId: string;
  containerId: string;
  pallets: string;
  packerName: string;
  onSet: (field: "bin_id" | "container_id" | "pallets" | "packer_name", value: string) => void;
};

function BinContainerSection({
  binId,
  containerId,
  pallets,
  packerName,
  onSet,
}: BinContainerProps) {
  return (
    <div className="border-t pt-5" style={{ borderColor: "var(--admin-border)" }}>
      <p
        className="text-xs font-semibold uppercase tracking-wider mb-3"
        style={{ color: "var(--admin-text-muted)" }}
      >
        Bin, Container &amp; Pallets
      </p>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label
            htmlFor="fld-8-bin-id"
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Bin ID
          </label>
          <input
            id="fld-8-bin-id"
            aria-label=". BIN 001"
            type="text"
            value={binId}
            onChange={(e) => onSet("bin_id", e.target.value)}
            placeholder="e.g. BIN-001"
            className="w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
        <div>
          <label
            htmlFor="fld-9-container-id"
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Container ID
          </label>
          <input
            id="fld-9-container-id"
            aria-label=". CONT A42"
            type="text"
            value={containerId}
            onChange={(e) => onSet("container_id", e.target.value)}
            placeholder="e.g. CONT-A42"
            className="w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
      </div>
      <div className="mt-3 grid grid-cols-2 gap-3">
        <div>
          <label
            htmlFor="fld-10-pallets"
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Pallets
          </label>
          <input
            id="fld-10-pallets"
            aria-label=". 4"
            type="number"
            value={pallets}
            onChange={(e) => onSet("pallets", e.target.value)}
            placeholder="e.g. 4"
            min="0"
            className="w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
        <div>
          <label
            htmlFor="fld-11-packer-name"
            className="block text-xs font-medium mb-1.5"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Packer Name
          </label>
          <input
            id="fld-11-packer-name"
            aria-label=". Jose R."
            type="text"
            value={packerName}
            onChange={(e) => onSet("packer_name", e.target.value)}
            placeholder="e.g. Jose R."
            className="w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-bg-subtle)",
              color: "var(--admin-text-primary)",
            }}
          />
        </div>
      </div>
    </div>
  );
}

// ── Subcomponent: NotesSection ──────────────────────────────────────────────
type NotesProps = {
  notes: string;
  notesOpen: boolean;
  onToggle: () => void;
  onSet: (value: string) => void;
};

function NotesSection({ notes, notesOpen, onToggle, onSet }: NotesProps) {
  return (
    <div className="border-t pt-5" style={{ borderColor: "var(--admin-border)" }}>
      <button
        type="button"
        onClick={onToggle}
        className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider transition-colors"
        style={{ color: "var(--admin-text-muted)" }}
        aria-label="Notes"
      >
        <span>Notes</span>
        <svg
          className="h-4 w-4"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth="2"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d={notesOpen ? "m18 15-6-6-6 6" : "m6 9 6 6 6-6"}
          />
        </svg>
      </button>
      {notesOpen && (
        <textarea
          aria-label="Spray Records, Weather Conditions, Or Other Harvest Details..."
          value={notes}
          onChange={(e) => onSet(e.target.value)}
          placeholder="Spray records, weather conditions, or other harvest details..."
          rows={3}
          className="mt-3 w-full rounded-xl border px-3 py-3 text-sm outline-none transition-colors resize-none"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-bg-subtle)",
            color: "var(--admin-text-primary)",
          }}
        />
      )}
    </div>
  );
}

// ── Subcomponent: FormActions ───────────────────────────────────────────────
type FormActionsProps = {
  onCancel: () => void;
  isPending: boolean;
  canSubmit: boolean;
};

function FormActions({ onCancel, isPending, canSubmit }: FormActionsProps) {
  return (
    <div
      className="flex items-center justify-end gap-3 border-t pt-5"
      style={{ borderColor: "var(--admin-border)" }}
    >
      <button
        type="button"
        onClick={onCancel}
        className="rounded-xl border px-6 py-3 text-sm font-semibold transition-colors"
        style={{
          borderColor: "var(--admin-border)",
          color: "var(--admin-text-muted)",
        }}
        aria-label="Cancel"
      >
        Cancel
      </button>
      <button
        type="submit"
        disabled={isPending || !canSubmit}
        className="rounded-xl px-8 py-3 text-base font-bold text-white transition-colors disabled:opacity-50 flex items-center gap-2"
        style={{ backgroundColor: "var(--admin-accent)" }}
      >
        {isPending ? (
          "Creating..."
        ) : (
          <>
            <svg
              className="h-4 w-4"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth="2"
            >
              <path d="M12 22V12M12 12C12 12 7 10 7 5c0-2.5 2.5-5 5-5s5 2.5 5 5c0 5-5 7-5 7z" />
            </svg>
            Create Lot
          </>
        )}
      </button>
    </div>
  );
}

// ── Main Component ──────────────────────────────────────────────────────────
export default function LotCreateModal({ isOpen, onClose, brandId }: Props) {
  const router = useRouter();
  const [isPending, startTransition] = useTransition();
  const [state, dispatch] = useReducer(reducer, initialState);

  // Reset the form on the closed → open transition only. A ref guard in the
  // if-test keeps this in the "tracked state change" bucket (legitimate
  // use of useEffect) rather than the "fake event handler" bucket.
  const prevIsOpenRef = useRef(false);
  useEffect(() => {
    if (isOpen && !prevIsOpenRef.current) {
      dispatch({ type: "RESET" });
    }
    prevIsOpenRef.current = isOpen;
  }, [isOpen]);

  if (!isOpen) return null;

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    dispatch({ type: "SET_ERROR", error: null });
    startTransition(async () => {
      const result = await createHarvestLot(brandId, {
        crop_type: state.crop_type,
        variety: state.variety || undefined,
        harvest_date: state.harvest_date,
        field_location: state.field_location || undefined,
        worker_name: state.worker_name || undefined,
        packer_name: state.packer_name || undefined,
        quantity_lbs: state.quantity_lbs ? Number(state.quantity_lbs) : undefined,
        notes: state.notes || undefined,
        bin_id: state.bin_id || undefined,
        container_id: state.container_id || undefined,
        field_block: state.field_block || undefined,
        yield_estimate_lbs: state.yield_estimate_lbs
          ? Number(state.yield_estimate_lbs)
          : undefined,
        yield_unit:
          state.yield_unit === "custom"
            ? state.customYieldUnit.trim() || undefined
            : state.yield_unit,
        pallets: state.pallets ? Number(state.pallets) : undefined,
      });
      if (result.success && result.lot) {
        onClose();
        router.push(`/admin/route-trace/lots/${result.lot.id}`);
      } else {
        dispatch({ type: "SET_ERROR", error: result.error ?? "Failed to create lot" });
      }
    });
  }

  function handleField<K extends keyof State>(field: K, value: State[K]) {
    if (typeof value === "string") {
      dispatch({ type: "SET_FIELD", field, value });
    }
  }

  const canSubmit = Boolean(state.crop_type && state.harvest_date && state.field_location);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
      {/* Backdrop */}
      <button
        type="button"
        aria-label="Close modal"
        className="absolute inset-0 bg-black/50 backdrop-blur-sm border-0 p-0 cursor-default"
        onClick={onClose}
      />

      {/* Modal */}
      <div
        className="relative w-full max-w-2xl max-h-[90vh] overflow-y-auto rounded-2xl border shadow-2xl"
        style={{
          backgroundColor: "white",
          borderColor: "var(--admin-border)",
        }}
      >
        <ModalHeader onClose={onClose} />

        <form onSubmit={handleSubmit} className="p-6 space-y-5">
          {state.error && <ErrorBanner message={state.error} />}

          <RequiredFieldsSection
            cropType={state.crop_type}
            variety={state.variety}
            harvestDate={state.harvest_date}
            onSet={(field, value) => handleField(field, value)}
          />

          <FieldLocationSection
            fieldLocation={state.field_location}
            fieldBlock={state.field_block}
            workerName={state.worker_name}
            onSet={(field, value) => handleField(field, value)}
          />

          <WeightYieldSection
            quantityLbs={state.quantity_lbs}
            yieldEstimateLbs={state.yield_estimate_lbs}
            yieldUnit={state.yield_unit}
            customYieldUnit={state.customYieldUnit}
            onSet={(field, value) => handleField(field, value)}
          />

          <BinContainerSection
            binId={state.bin_id}
            containerId={state.container_id}
            pallets={state.pallets}
            packerName={state.packer_name}
            onSet={(field, value) => handleField(field, value)}
          />

          <NotesSection
            notes={state.notes}
            notesOpen={state.notesOpen}
            onToggle={() => dispatch({ type: "TOGGLE_NOTES" })}
            onSet={(value) => dispatch({ type: "SET_FIELD", field: "notes", value })}
          />

          <FormActions
            onCancel={onClose}
            isPending={isPending}
            canSubmit={canSubmit}
          />
        </form>
      </div>
    </div>
  );
}
