"use client";

import { useReducer } from "react";
import { useRouter } from "next/navigation";
import { updateWaterIrrigator, resetWaterIrrigatorPin, deleteWaterUser } from "@/actions/water-log/admin";
import AdminButton from "./design-system/AdminButton";

type WaterUser = {
  id: string;
  name: string;
  role: "irrigator" | "water_admin";
  active: boolean;
  language_preference: string;
  last_used_at: string | null;
  created_at: string;
};

type Props = {
  waterUser: WaterUser;
  backHref?: string;
};

type Draft = {
  name?: string;
  role?: "irrigator" | "water_admin";
  active?: boolean;
  lang?: string;
};

type State = {
  draft: Draft;
  saving: boolean;
  deleting: boolean;
  resetting: boolean;
  newPin: string | null;
  error: string | null;
};

type Action =
  | { type: "SET_NAME"; value: string }
  | { type: "SET_ROLE"; value: "irrigator" | "water_admin" }
  | { type: "SET_ACTIVE"; value: boolean }
  | { type: "SET_LANG"; value: string }
  | { type: "START_SAVE" }
  | { type: "SAVE_FAIL"; error: string }
  | { type: "START_DELETE" }
  | { type: "DELETE_FAIL"; error: string }
  | { type: "START_RESET_PIN" }
  | { type: "RESET_PIN_SUCCESS"; pin: string }
  | { type: "RESET_PIN_FAIL"; error: string }
  | { type: "DISMISS_PIN" }
  | { type: "SET_ERROR"; error: string | null };

const initialState: State = {
  draft: {},
  saving: false,
  deleting: false,
  resetting: false,
  newPin: null,
  error: null,
};

function reducer(state: State, action: Action): State {
  switch (action.type) {
    case "SET_NAME":
      return { ...state, draft: { ...state.draft, name: action.value } };
    case "SET_ROLE":
      return { ...state, draft: { ...state.draft, role: action.value } };
    case "SET_ACTIVE":
      return { ...state, draft: { ...state.draft, active: action.value } };
    case "SET_LANG":
      return { ...state, draft: { ...state.draft, lang: action.value } };
    case "START_SAVE":
      return { ...state, saving: true, error: null };
    case "SAVE_FAIL":
      return { ...state, saving: false, error: action.error };
    case "START_DELETE":
      return { ...state, deleting: true, error: null };
    case "DELETE_FAIL":
      return { ...state, deleting: false, error: action.error };
    case "START_RESET_PIN":
      return { ...state, resetting: true, error: null };
    case "RESET_PIN_SUCCESS":
      return { ...state, resetting: false, newPin: action.pin };
    case "RESET_PIN_FAIL":
      return { ...state, resetting: false, error: action.error };
    case "DISMISS_PIN":
      return { ...state, newPin: null };
    case "SET_ERROR":
      return { ...state, error: action.error };
  }
}

export default function WaterUserEditForm({ waterUser, backHref = "/admin/water-log" }: Props) {
  const router = useRouter();
  const [state, dispatch] = useReducer(reducer, initialState);

  // Holds user edits only; missing keys fall back to the current prop so we
  // never copy the prop into useState. When the prop changes, the fallback
  // value tracks the new prop automatically.
  const name = state.draft.name ?? waterUser.name;
  const role = state.draft.role ?? waterUser.role;
  const active = state.draft.active ?? waterUser.active;
  const lang = state.draft.lang ?? waterUser.language_preference;

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    dispatch({ type: "START_SAVE" });
    const result = await updateWaterIrrigator(waterUser.id, name.trim(), active, lang, role);
    if (result.success) {
      router.push(backHref);
    } else {
      dispatch({ type: "SAVE_FAIL", error: result.error ?? "Failed to save" });
    }
  }

  async function handleResetPin() {
    dispatch({ type: "START_RESET_PIN" });
    const result = await resetWaterIrrigatorPin(waterUser.id);
    if (result.success && result.pin) {
      dispatch({ type: "RESET_PIN_SUCCESS", pin: result.pin });
    } else {
      dispatch({ type: "RESET_PIN_FAIL", error: result.error ?? "Failed to reset PIN" });
    }
  }

  async function handleDelete() {
    if (!window.confirm(`Delete user "${waterUser.name}"? Their log entries will be preserved.`)) return;
    dispatch({ type: "START_DELETE" });
    const result = await deleteWaterUser(waterUser.id);
    if (result.success) {
      router.push(backHref);
    } else {
      dispatch({ type: "DELETE_FAIL", error: result.error ?? "Failed to delete" });
    }
  }

  return (
    <form onSubmit={handleSave} className="space-y-4">
      {state.error && (
        <div className="rounded-lg bg-red-100 border border-red-200 p-3 text-sm text-red-700">
          {state.error}
        </div>
      )}

      {state.newPin && (
        <div className="rounded-xl bg-amber-100 border border-amber-200 p-4">
          <p className="font-semibold text-amber-800">New PIN for {name}:</p>
          <p className="mt-1 text-2xl font-bold tracking-widest text-amber-900">{state.newPin}</p>
          <p className="mt-1 text-xs text-amber-600">Write this down — it will not be shown again.</p>
          <button type="button" onClick={() => dispatch({ type: "DISMISS_PIN" })} className="mt-2 text-xs text-amber-700 underline">Dismiss</button>
        </div>
      )}

      <div className="grid grid-cols-3 gap-4">
        <div>
          <label htmlFor="fld-1-name"  className="block text-sm font-medium text-[var(--admin-text-muted)] mb-1">Name</label>
          <input id="fld-1-name"  aria-label="Text"
            type="text"
            value={name}
            onChange={(e) => dispatch({ type: "SET_NAME", value: e.target.value })}
            className="w-full rounded-lg border border-[var(--admin-border)] px-3 py-2 text-sm outline-none focus:border-[var(--admin-accent)]"
            required
          />
        </div>
        <div>
          <label htmlFor="fld-2-role"  className="block text-sm font-medium text-[var(--admin-text-muted)] mb-1">Role</label>
          <select id="fld-2-role"  aria-label="Select"
            value={role}
            onChange={(e) => dispatch({ type: "SET_ROLE", value: e.target.value as "irrigator" | "water_admin" })}
            className="w-full rounded-lg border border-[var(--admin-border)] px-3 py-2 text-sm"
          >
            <option value="irrigator">Irrigator</option>
            <option value="water_admin">Admin</option>
          </select>
          <p className="text-xs text-[var(--admin-text-muted)] mt-0.5">
            {role === "water_admin"
              ? "Can manage headgates, users, and entries"
              : "Can only submit water log entries"}
          </p>
        </div>
        <div>
          <label htmlFor="fld-3-language"  className="block text-sm font-medium text-[var(--admin-text-muted)] mb-1">Language</label>
          <select id="fld-3-language"  aria-label="Select"
            value={lang}
            onChange={(e) => dispatch({ type: "SET_LANG", value: e.target.value })}
            className="w-full rounded-lg border border-[var(--admin-border)] px-3 py-2 text-sm"
          >
            <option value="en">English</option>
            <option value="es">Español</option>
          </select>
        </div>
      </div>

      <div className="flex items-center gap-4">
        <div>
          <label htmlFor="fld-4-status"  className="block text-sm font-medium text-[var(--admin-text-muted)] mb-1">Status</label>
          <select id="fld-4-status"  aria-label="Select"
            value={active ? "1" : "0"}
            onChange={(e) => dispatch({ type: "SET_ACTIVE", value: e.target.value === "1" })}
            className="rounded-lg border border-[var(--admin-border)] px-3 py-2 text-sm"
          >
            <option value="1">Active</option>
            <option value="0">Inactive</option>
          </select>
        </div>
        <div className="pt-4">
          <AdminButton
            type="button"
            variant="secondary"
            onClick={handleResetPin}
            disabled={state.resetting}
            isLoading={state.resetting}
          >
            Reset PIN
          </AdminButton>
        </div>
      </div>

      <div className="flex items-center justify-between pt-2">
        <AdminButton
          type="button"
          variant="danger"
          onClick={handleDelete}
          disabled={state.deleting}
          isLoading={state.deleting}
        >
          Delete User
        </AdminButton>
        <AdminButton
          type="submit"
          disabled={state.saving}
          isLoading={state.saving}
        >
          Save Changes
        </AdminButton>
      </div>
    </form>
  );
}