"use client";

import { useActionState, useState, type FormEvent } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { FREQUENCY_LABELS } from "@/lib/schedule";
import {
  ENABLED_FREQUENCIES,
  SLOW_THRESHOLD_LIMITS,
  settingsFormValues,
  validateSettings,
  type SettingsFieldErrors,
  type SettingsFormValues,
} from "@/lib/validation/settings";
import { updateSettingsAction, type SettingsFormState } from "@/app/(dashboard)/settings/actions";

const selectClass =
  "h-9 w-full rounded-md border border-slate-300 bg-white px-2.5 text-sm text-slate-900 focus-visible:border-slate-900 focus-visible:outline-1 focus-visible:outline-slate-900 aria-invalid:border-red-500";

export function SettingsForm({ initialValues, timezones }: { initialValues: SettingsFormValues; timezones: string[] }) {
  const [state, formAction, pending] = useActionState<SettingsFormState, FormData>(updateSettingsAction, {});
  const [clientErrors, setClientErrors] = useState<SettingsFieldErrors | null>(null);

  const values = state.values ?? initialValues;
  const errors = clientErrors ?? state.fieldErrors ?? {};

  function handleSubmit(event: FormEvent<HTMLFormElement>) {
    const result = validateSettings(settingsFormValues(new FormData(event.currentTarget)));
    if (result.ok) return setClientErrors(null);
    event.preventDefault();
    setClientErrors(result.fieldErrors);
  }

  return (
    <form action={formAction} onSubmit={handleSubmit} noValidate className="space-y-5">
      {state.error && (
        <p role="alert" className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
          {state.error}
        </p>
      )}

      <div className="grid gap-5 sm:grid-cols-3">
        <div className="space-y-1.5">
          <Label htmlFor="frequency">Check Frequency</Label>
          <select
            id="frequency"
            name="frequency"
            defaultValue={values.frequency}
            className={selectClass}
            aria-invalid={Boolean(errors.frequency)}
          >
            {ENABLED_FREQUENCIES.map((frequency) => (
              <option key={frequency} value={frequency}>
                {FREQUENCY_LABELS[frequency]}
              </option>
            ))}
          </select>
          {errors.frequency && <p className="text-xs text-red-600">{errors.frequency}</p>}
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="checkTime">Check Time</Label>
          <Input
            id="checkTime"
            name="checkTime"
            type="time"
            required
            defaultValue={values.checkTime}
            aria-invalid={Boolean(errors.checkTime)}
          />
          {errors.checkTime && <p className="text-xs text-red-600">{errors.checkTime}</p>}
        </div>

        <div className="space-y-1.5">
          <Label htmlFor="timezone">Timezone</Label>
          <select
            id="timezone"
            name="timezone"
            defaultValue={values.timezone}
            className={selectClass}
            aria-invalid={Boolean(errors.timezone)}
          >
            {timezones.map((timezone) => (
              <option key={timezone} value={timezone}>
                {timezone.replaceAll("_", " ")}
              </option>
            ))}
          </select>
          {errors.timezone && <p className="text-xs text-red-600">{errors.timezone}</p>}
        </div>
      </div>

      <p className="-mt-2 text-xs text-slate-500">The timezone is also used to display every date and time in the dashboard.</p>

      <div className="grid gap-5 border-t border-slate-200 pt-5 sm:grid-cols-3">
        <div className="space-y-1.5">
          <Label htmlFor="slowThresholdSeconds">Slow-response threshold (seconds)</Label>
          <Input
            id="slowThresholdSeconds"
            name="slowThresholdSeconds"
            inputMode="numeric"
            required
            defaultValue={values.slowThresholdSeconds}
            aria-invalid={Boolean(errors.slowThresholdSeconds)}
            aria-describedby="slowThresholdSeconds-hint"
          />
          {errors.slowThresholdSeconds ? (
            <p className="text-xs text-red-600">{errors.slowThresholdSeconds}</p>
          ) : (
            <p id="slowThresholdSeconds-hint" className="text-xs text-slate-500">
              {SLOW_THRESHOLD_LIMITS.min}–{SLOW_THRESHOLD_LIMITS.max}. An app that answers correctly but slower than this is
              shown as Slow Response. Each app&apos;s timeout should be longer than this value.
            </p>
          )}
        </div>
      </div>

      <div className="flex items-center justify-between gap-3 border-t border-slate-200 pt-4">
        <p className="text-xs text-slate-500">Changes to the threshold apply from the next health check.</p>
        <div className="flex items-center gap-3">
          {state.saved && !pending && (
            <span role="status" className="text-xs font-medium text-emerald-700">
              Saved
            </span>
          )}
          <Button type="submit" disabled={pending}>
            {pending ? "Saving…" : "Save Settings"}
          </Button>
        </div>
      </div>
    </form>
  );
}
