"use client";

import { useReducer, useTransition } from "react";
import { createHarvestLot } from "@/actions/route-trace/lots";
import GlassModal from "@/components/admin/GlassModal";

// Plant icon for the modal title - consistent one-color outline style
const PlantIcon = ({ className }: { className?: string }) => (
  <svg
    className={className ?? "w-5 h-5"}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="2"
    strokeLinecap="round"
    strokeLinejoin="round"
    style={{ color: "var(--admin-accent)" }}
  >
    <path d="M7 20h10"/>
    <path d="M10 20c5.5-2.5.8-6.4 3-10"/>
    <path d="M9.5 9.4c1.1.8 1.8 2.2 2.3 3.7-2 .4-3.5.4-4.8-.3-1.2-.6-2.3-1.9-3-4.2 2.8-.5 4.4 0 5.5.8z"/>
    <path d="M14.1 6a7 7 0 0 0-1.1 4c1.9-.1 3.3-.6 4.3-1.4 1-1 1.6-2.3 1.7-4.6-2.7.1-4 1-4.9 2z"/>
  </svg>
);

type Props = {
  brandId: string;
  onCreated: (lotId: string) => void;
  onClose: () => void;
};

const TODAY = new Date().toISOString().split("T")[0];

type State = {
  error: string | null;
  crop_type: string;
  harvest_date: string;
  field_location: string;
  worker_name: string;
  quantity_lbs: string;
  variety: string;
};

type Action =
  | { type: "SET_ERROR"; value: string | null }
  | { type: "SET_CROP_TYPE"; value: string }
  | { type: "SET_HARVEST_DATE"; value: string }
  | { type: "SET_FIELD_LOCATION"; value: string }
  | { type: "SET_WORKER_NAME"; value: string }
  | { type: "SET_QUANTITY_LBS"; value: string }
  | { type: "SET_VARIETY"; value: string };

const initialState: State = {
  error: null,
  crop_type: "",
  harvest_date: TODAY,
  field_location: "",
  worker_name: "",
  quantity_lbs: "",
  variety: "",
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_ERROR":
      return { ...state, error: action.value };
    case "SET_CROP_TYPE":
      return { ...state, crop_type: action.value };
    case "SET_HARVEST_DATE":
      return { ...state, harvest_date: action.value };
    case "SET_FIELD_LOCATION":
      return { ...state, field_location: action.value };
    case "SET_WORKER_NAME":
      return { ...state, worker_name: action.value };
    case "SET_QUANTITY_LBS":
      return { ...state, quantity_lbs: action.value };
    case "SET_VARIETY":
      return { ...state, variety: action.value };
  }
}

export default function QuickNewLotModal({ brandId, onCreated, onClose }: Props) {
  const [isPending, startTransition] = useTransition();
  const [state, dispatch] = useReducer(reducer, initialState);

  function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!state.crop_type.trim()) return;
    dispatch({ type: "SET_ERROR", value: null });

    startTransition(async () => {
      const result = await createHarvestLot(brandId, {
        crop_type: state.crop_type.trim(),
        harvest_date: state.harvest_date || TODAY,
        field_location: state.field_location.trim() || undefined,
        worker_name: state.worker_name.trim() || undefined,
        variety: state.variety.trim() || undefined,
        quantity_lbs: state.quantity_lbs ? Number(state.quantity_lbs) : undefined,
      });
      if (result.success && result.lot) {
        onCreated(result.lot.id);
      } else {
        dispatch({ type: "SET_ERROR", value: result.error ?? "Failed to create lot" });
      }
    });
  }

  return (
    <GlassModal
      title="New Harvest Lot"
      titleIcon={<PlantIcon className="w-5 h-5" />}
      subtitle="Quick entry — scan or fill in the fields below"
      onClose={onClose}
    >
      <form onSubmit={submit} className="space-y-4">
        {state.error && (
          <div className="rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700">
            {state.error}
          </div>
        )}

        <div>
          <label className="block text-sm font-medium text-stone-700 mb-1.5" htmlFor="fld-crop-type-">
            Crop Type <span className="text-red-500">*</span>
          </label>
          <input id="fld-crop-type-" aria-label=". Sweet Corn"
            type="text"
            value={state.crop_type}
            onChange={(e) => dispatch({ type: "SET_CROP_TYPE", value: e.target.value })}
            placeholder="e.g. Sweet Corn"
            required
            className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-base text-stone-900 placeholder:text-stone-400 focus:outline-none focus:border-stone-400 focus:bg-white transition-colors"
          />
        </div>

        <div>
          <label htmlFor="fld-1-harvest-date"  className="block text-sm font-medium text-stone-700 mb-1.5">Harvest Date</label>
          <input id="fld-1-harvest-date"  aria-label="Date"
            type="date"
            value={state.harvest_date}
            onChange={(e) => dispatch({ type: "SET_HARVEST_DATE", value: e.target.value })}
            className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-base text-stone-900 focus:outline-none focus:border-stone-400 focus:bg-white transition-colors"
          />
        </div>

        <div>
          <label htmlFor="fld-2-field-location"  className="block text-sm font-medium text-stone-700 mb-1.5">Field / Location</label>
          <input id="fld-2-field-location"  aria-label=". North Field"
            type="text"
            value={state.field_location}
            onChange={(e) => dispatch({ type: "SET_FIELD_LOCATION", value: e.target.value })}
            placeholder="e.g. North Field"
            className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-base text-stone-900 placeholder:text-stone-400 focus:outline-none focus:border-stone-400 focus:bg-white transition-colors"
          />
        </div>

        <div className="grid grid-cols-2 gap-3">
          <div>
            <label htmlFor="fld-3-worker"  className="block text-sm font-medium text-stone-700 mb-1.5">Worker</label>
            <input id="fld-3-worker"  aria-label="Name"
              type="text"
              value={state.worker_name}
              onChange={(e) => dispatch({ type: "SET_WORKER_NAME", value: e.target.value })}
              placeholder="Name"
              className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-base text-stone-900 placeholder:text-stone-400 focus:outline-none focus:border-stone-400 focus:bg-white transition-colors"
            />
          </div>
          <div>
            <label htmlFor="fld-4-variety"  className="block text-sm font-medium text-stone-700 mb-1.5">Variety</label>
            <input id="fld-4-variety"  aria-label="Type"
              type="text"
              value={state.variety}
              onChange={(e) => dispatch({ type: "SET_VARIETY", value: e.target.value })}
              placeholder="Type"
              className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-base text-stone-900 placeholder:text-stone-400 focus:outline-none focus:border-stone-400 focus:bg-white transition-colors"
            />
          </div>
        </div>

        <div>
          <label htmlFor="fld-5-quantity-lbs"  className="block text-sm font-medium text-stone-700 mb-1.5">Quantity (lbs)</label>
          <input id="fld-5-quantity-lbs"  aria-label="0"
            type="number"
            value={state.quantity_lbs}
            onChange={(e) => dispatch({ type: "SET_QUANTITY_LBS", value: e.target.value })}
            placeholder="0"
            min="0"
            className="w-full rounded-xl border border-stone-200 bg-stone-50 px-4 py-3 text-base text-stone-900 focus:outline-none focus:border-stone-400 focus:bg-white transition-colors"
          />
        </div>

        <button
          type="submit"
          disabled={isPending || !state.crop_type.trim()}
          className="w-full rounded-xl bg-stone-800 py-3.5 text-base font-semibold text-white hover:bg-stone-700 disabled:opacity-50 transition-colors mt-2"
        >
          {isPending ? "Creating..." : "Create Lot"}
        </button>
      </form>
    </GlassModal>
  );
}
