"use client";

import { useReducer } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { createStop } from "@/actions/stops/create-stop";
import { AdminInput,  AdminTextInput, AdminSelect  } from "./design-system/AdminFormElements";
import AdminButton from "./design-system/AdminButton";
import { useToast } from "./Toast";

type Stop = {
  city: string;
  state: string;
  location: string;
  date: string;
  time: string;
  brand_id: string;
  active: boolean;
  address?: string | null;
  zip?: string | null;
  cutoff_time?: string | null;
};

type Props = {
  duplicateFrom?: Stop | null;
};

type FormFields = {
  city: string;
  state: string;
  location: string;
  date: string;
  time: string;
  brandId: string;
  active: string;
  address: string;
  zip: string;
  cutoffTime: string;
};

type State = FormFields & {
  loading: boolean;
  error: string | null;
  fieldErrors: Record<string, string>;
};

type Action =
  | { type: "SET_FIELD"; field: keyof FormFields; value: string }
  | { type: "SET_FIELD_ERRORS"; errors: Record<string, string> }
  | { type: "SET_LOADING"; value: boolean }
  | { type: "SET_ERROR"; error: string | null };

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_FIELD": {
      const nextErrors = { ...state.fieldErrors };
      delete nextErrors[action.field];
      return {
        ...state,
        [action.field]: action.value,
        fieldErrors: nextErrors,
      };
    }
    case "SET_FIELD_ERRORS":
      return { ...state, fieldErrors: action.errors };
    case "SET_LOADING":
      return { ...state, loading: action.value };
    case "SET_ERROR":
      return { ...state, error: action.error };
    default:
      return state;
  }
}

const DEFAULT_BRAND = "64294306-5f42-463d-a5e8-2ad6c81a96de";

function validate(s: State): Record<string, string> {
  const errors: Record<string, string> = {};
  if (!s.city.trim()) errors.city = "City is required";
  if (!s.state.trim()) errors.state = "State is required";
  if (!s.location.trim()) errors.location = "Location is required";
  if (!s.date.trim()) errors.date = "Date is required";
  if (!s.time.trim()) errors.time = "Time is required";
  if (!s.brandId) errors.brandId = "Brand is required";
  return errors;
}

export default function NewStopForm({ duplicateFrom }: Props) {
  const router = useRouter();
  const { success: showSuccess, error: showError } = useToast();

  const [state, dispatch] = useReducer(reducer, duplicateFrom ?? null, (df): State => ({
    city: df?.city ?? "",
    state: df?.state ?? "",
    location: df?.location ?? "",
    date: df?.date ?? "",
    time: df?.time ?? "",
    brandId: df?.brand_id ?? DEFAULT_BRAND,
    active: "true",
    address: df?.address ?? "",
    zip: df?.zip ?? "",
    cutoffTime: df?.cutoff_time ?? "",
    loading: false,
    error: null,
    fieldErrors: {},
  }));

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();

    const errors = validate(state);
    if (Object.keys(errors).length > 0) {
      dispatch({ type: "SET_FIELD_ERRORS", errors });
      showError("Validation failed", "Please fix the errors below");
      return;
    }

    dispatch({ type: "SET_LOADING", value: true });
    dispatch({ type: "SET_ERROR", error: null });

    const result = await createStop(state.brandId, {
      city: state.city,
      state: state.state,
      location: state.location,
      date: state.date,
      time: state.time,
      active: state.active === "true",
      address: state.address || null,
      zip: state.zip || null,
      cutoff_time: state.cutoffTime || null,
    });

    if (!result.success) {
      showError("Failed to create stop", result.error ?? "Please try again");
      dispatch({ type: "SET_ERROR", error: result.error ?? "Failed to create stop" });
      dispatch({ type: "SET_LOADING", value: false });
      return;
    }

    showSuccess("Stop created", `${state.city}, ${state.state} has been added`);

    if (result.id) {
      router.push(`/admin/stops/${result.id}`);
    } else {
      router.push("/admin/stops");
    }
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="mt-8 max-w-xl space-y-6">
      {state.error && <ErrorBanner message={state.error} />}

      <LocationFields
        city={state.city}
        state={state.state}
        fieldErrors={state.fieldErrors}
        dispatch={dispatch}
      />

      <LocationNameField
        location={state.location}
        fieldErrors={state.fieldErrors}
        dispatch={dispatch}
      />

      <DateTimeFields
        date={state.date}
        time={state.time}
        fieldErrors={state.fieldErrors}
        dispatch={dispatch}
      />

      <BrandField
        brandId={state.brandId}
        fieldErrors={state.fieldErrors}
        dispatch={dispatch}
      />

      <ActiveField
        active={state.active}
        dispatch={dispatch}
      />

      <AddressFields
        address={state.address}
        zip={state.zip}
        dispatch={dispatch}
      />

      <CutoffField
        cutoffTime={state.cutoffTime}
        dispatch={dispatch}
      />

      <FormActions loading={state.loading} />
    </form>
  );
}

function ErrorBanner({ message }: { message: string }) {
  return (
    <div className="rounded-xl bg-red-50 border border-red-200 p-4 text-sm text-red-600 flex items-start gap-3">
      <svg className="h-5 w-5 shrink-0 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
        <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      {message}
    </div>
  );
}

function LocationFields({
  city,
  state,
  fieldErrors,
  dispatch,
}: {
  city: string;
  state: string;
  fieldErrors: Record<string, string>;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div className="grid grid-cols-2 gap-4">
      <div>
        <label htmlFor="fld-city" className="block text-xs font-semibold text-stone-700 mb-1.5">
          City <span className="text-red-500">*</span>
        </label>
        <input id="fld-city" aria-label=". Denver"
          type="text"
          value={city}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "city", value: e.target.value })}
          placeholder="e.g. Denver"
          className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
            fieldErrors.city
              ? "border-red-400 bg-red-50"
              : "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
          }`}
        />
        {fieldErrors.city && <p className="mt-1 text-xs text-red-500">{fieldErrors.city}</p>}
      </div>

      <div>
        <label htmlFor="fld-state" className="block text-xs font-semibold text-stone-700 mb-1.5">
          State <span className="text-red-500">*</span>
        </label>
        <input id="fld-state" aria-label=". CO"
          type="text"
          value={state}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "state", value: e.target.value })}
          placeholder="e.g. CO"
          className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
            fieldErrors.state
              ? "border-red-400 bg-red-50"
              : "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
          }`}
        />
        {fieldErrors.state && <p className="mt-1 text-xs text-red-500">{fieldErrors.state}</p>}
      </div>
    </div>
  );
}

function LocationNameField({
  location,
  fieldErrors,
  dispatch,
}: {
  location: string;
  fieldErrors: Record<string, string>;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div>
      <label htmlFor="fld-location-name" className="block text-xs font-semibold text-stone-700 mb-1.5">
        Location Name <span className="text-red-500">*</span>
      </label>
      <input id="fld-location-name" aria-label=". Southwest Plaza Parking Lot"
        type="text"
        value={location}
        onChange={(e) => dispatch({ type: "SET_FIELD", field: "location", value: e.target.value })}
        placeholder="e.g. Southwest Plaza Parking Lot"
        className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
          fieldErrors.location
            ? "border-red-400 bg-red-50"
            : "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
        }`}
      />
      {fieldErrors.location && <p className="mt-1 text-xs text-red-500">{fieldErrors.location}</p>}
    </div>
  );
}

function DateTimeFields({
  date,
  time,
  fieldErrors,
  dispatch,
}: {
  date: string;
  time: string;
  fieldErrors: Record<string, string>;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div className="grid grid-cols-2 gap-4">
      <div>
        <label htmlFor="fld-date" className="block text-xs font-semibold text-stone-700 mb-1.5">
          Date <span className="text-red-500">*</span>
        </label>
        <input id="fld-date" aria-label="Date"
          type="date"
          value={date}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "date", value: e.target.value })}
          className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
            fieldErrors.date
              ? "border-red-400 bg-red-50"
              : "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
          }`}
        />
        {fieldErrors.date && <p className="mt-1 text-xs text-red-500">{fieldErrors.date}</p>}
      </div>

      <div>
        <label htmlFor="fld-time" className="block text-xs font-semibold text-stone-700 mb-1.5">
          Time <span className="text-red-500">*</span>
        </label>
        <input id="fld-time" aria-label=". 8:00 AM – 2:00 PM"
          type="text"
          value={time}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "time", value: e.target.value })}
          placeholder="e.g. 8:00 AM – 2:00 PM"
          className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
            fieldErrors.time
              ? "border-red-400 bg-red-50"
              : "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
          }`}
        />
        {fieldErrors.time && <p className="mt-1 text-xs text-red-500">{fieldErrors.time}</p>}
      </div>
    </div>
  );
}

function BrandField({
  brandId,
  fieldErrors,
  dispatch,
}: {
  brandId: string;
  fieldErrors: Record<string, string>;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div>
      <label htmlFor="fld-brand" className="block text-xs font-semibold text-stone-700 mb-1.5">
        Brand <span className="text-red-500">*</span>
      </label>
      <select id="fld-brand" aria-label="Select"
        value={brandId}
        onChange={(e) => dispatch({ type: "SET_FIELD", field: "brandId", value: e.target.value })}
        className={`w-full rounded-xl border px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:ring-2 focus:ring-[var(--admin-accent)]/20 ${
          fieldErrors.brandId
            ? "border-red-400 bg-red-50"
            : "border-[var(--admin-border)] bg-white focus:border-[var(--admin-accent)]"
        }`}
      >
        <option value="">Select brand...</option>
        <option value="64294306-5f42-463d-a5e8-2ad6c81a96de">Tuxedo Corn</option>
        <option value="b1cb7a96-d82b-40b1-80b1-d6dd26c56e28">Indian River Direct</option>
      </select>
      {fieldErrors.brandId && <p className="mt-1 text-xs text-red-500">{fieldErrors.brandId}</p>}
    </div>
  );
}

function ActiveField({
  active,
  dispatch,
}: {
  active: string;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div>
      <label htmlFor="fld-1-active"  className="block text-xs font-semibold text-stone-700 mb-1.5">Active</label>
      <select id="fld-1-active"  aria-label="Select"
        value={active}
        onChange={(e) => dispatch({ type: "SET_FIELD", field: "active", value: e.target.value })}
        className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
      >
        <option value="true">Yes — show on storefront</option>
        <option value="false">No — hide from storefront</option>
      </select>
    </div>
  );
}

function AddressFields({
  address,
  zip,
  dispatch,
}: {
  address: string;
  zip: string;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div className="grid grid-cols-2 gap-4">
      <div>
        <label htmlFor="fld-2-street-address"  className="block text-xs font-semibold text-stone-700 mb-1.5">Street Address</label>
        <input id="fld-2-street-address"  aria-label="123 Main St"
          type="text"
          value={address}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "address", value: e.target.value })}
          placeholder="123 Main St"
          className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
        />
      </div>

      <div>
        <label htmlFor="fld-3-zip-code"  className="block text-xs font-semibold text-stone-700 mb-1.5">ZIP Code</label>
        <input id="fld-3-zip-code"  aria-label="80102"
          type="text"
          value={zip}
          onChange={(e) => dispatch({ type: "SET_FIELD", field: "zip", value: e.target.value })}
          placeholder="80102"
          maxLength={10}
          className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
        />
      </div>
    </div>
  );
}

function CutoffField({
  cutoffTime,
  dispatch,
}: {
  cutoffTime: string;
  dispatch: React.Dispatch<Action>;
}) {
  return (
    <div>
      <label htmlFor="fld-cutoff" className="block text-xs font-semibold text-stone-700 mb-1.5">Order Cutoff</label>
      <p className="text-[10px] text-stone-500 mb-2">Customers must order before this time to be included at this stop.</p>
      <input id="fld-cutoff" aria-label="Datetime Local"
        type="datetime-local"
        value={cutoffTime}
        onChange={(e) => dispatch({ type: "SET_FIELD", field: "cutoffTime", value: e.target.value })}
        className="w-full rounded-xl border border-[var(--admin-border)] bg-white px-3 py-2.5 text-sm text-[var(--admin-text-primary)] outline-none focus:border-[var(--admin-accent)] focus:ring-2 focus:ring-[var(--admin-accent)]/20"
      />
    </div>
  );
}

function FormActions({ loading }: { loading: boolean }) {
  return (
    <div className="flex gap-3">
      <AdminButton
        type="submit"
        disabled={loading}
        isLoading={loading}
        variant="primary"
        size="lg"
      >
        {loading ? "Creating..." : "Create Stop"}
      </AdminButton>

      <Link
        href="/admin/stops"
        className="rounded-xl border border-[var(--admin-border)] px-6 py-3 font-medium text-stone-600 hover:bg-stone-50 transition-colors"
      >
        Cancel
      </Link>
    </div>
  );
}