"use client";

import { useActionState, useEffect, type ReactNode } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { nativeSelectClassName } from "@/components/fichas/form-fields";
import { bitacoraCategoriaOptions, bitacoraEstadoOptions, bitacoraPrioridadOptions, formatTags } from "@/lib/bitacora";
import { bitacoraInitialState } from "@/lib/bitacora-state";
import { saveBitacoraHitoAction } from "@/server/actions/bitacora";

type BitacoraFormProps = {
  mode: "create" | "edit";
  hito?: {
    id: string;
    titulo: string;
    descripcion: string | null;
    fechaHito: Date;
    categoria: string;
    estado: string;
    prioridad: string;
    organismo: string | null;
    ubicacion: string | null;
    responsable: string | null;
    etiquetas: string[];
    destacado: boolean;
    visiblePublico: boolean;
  };
  submitLabel?: string;
};

export function BitacoraForm({ mode, hito, submitLabel }: BitacoraFormProps) {
  const router = useRouter();
  const [state, formAction] = useActionState(saveBitacoraHitoAction.bind(null, hito?.id ?? null), bitacoraInitialState);

  useEffect(() => {
    if (!state.message) return;
    if (state.success) {
      toast.success(state.message);
      if (mode === "create" && state.redirectTo) {
        router.push(state.redirectTo);
      } else {
        router.refresh();
      }
    } else {
      toast.error(state.message);
    }
  }, [mode, router, state.message, state.redirectTo, state.success]);

  return (
    <Card className="border-border shadow-sm">
      <CardHeader>
        <CardTitle>{mode === "create" ? "Nuevo hito" : "Editar hito"}</CardTitle>
      </CardHeader>
      <CardContent>
        <form action={formAction} className="space-y-6">
          <div className="grid gap-4 md:grid-cols-2">
            <Field label="Título" error={state.errors?.titulo?.[0]}>
              <Input name="titulo" defaultValue={state.formValues?.titulo?.toString() ?? hito?.titulo ?? ""} />
            </Field>
            <Field label="Fecha del hito" error={state.errors?.fechaHito?.[0]}>
              <Input
                type="date"
                name="fechaHito"
                defaultValue={state.formValues?.fechaHito?.toString() ?? dateToInput(hito?.fechaHito)}
              />
            </Field>
            <Field label="Categoría" error={state.errors?.categoria?.[0]}>
              <select name="categoria" defaultValue={state.formValues?.categoria?.toString() ?? (hito?.categoria ?? "")} className={nativeSelectClassName}>
                <option value="">Seleccione</option>
                {bitacoraCategoriaOptions.map((option) => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </Field>
            <Field label="Estado" error={state.errors?.estado?.[0]}>
              <select name="estado" defaultValue={state.formValues?.estado?.toString() ?? (hito?.estado ?? "PENDIENTE")} className={nativeSelectClassName}>
                {bitacoraEstadoOptions.map((option) => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </Field>
            <Field label="Prioridad" error={state.errors?.prioridad?.[0]}>
              <select name="prioridad" defaultValue={state.formValues?.prioridad?.toString() ?? (hito?.prioridad ?? "MEDIA")} className={nativeSelectClassName}>
                {bitacoraPrioridadOptions.map((option) => (
                  <option key={option.value} value={option.value}>{option.label}</option>
                ))}
              </select>
            </Field>
            <Field label="Responsable" error={state.errors?.responsable?.[0]}>
              <Input name="responsable" defaultValue={state.formValues?.responsable?.toString() ?? hito?.responsable ?? ""} />
            </Field>
            <Field label="Organismo" error={state.errors?.organismo?.[0]}>
              <Input name="organismo" defaultValue={state.formValues?.organismo?.toString() ?? hito?.organismo ?? ""} />
            </Field>
            <Field label="Ubicación" error={state.errors?.ubicacion?.[0]}>
              <Input name="ubicacion" defaultValue={state.formValues?.ubicacion?.toString() ?? hito?.ubicacion ?? ""} />
            </Field>
          </div>

          <Field label="Descripción" error={state.errors?.descripcion?.[0]}>
            <Textarea name="descripcion" rows={5} defaultValue={state.formValues?.descripcion?.toString() ?? hito?.descripcion ?? ""} />
          </Field>

          <Field label="Etiquetas" hint="Separadas por coma" error={state.errors?.etiquetas?.[0]}>
            <Input name="etiquetas" defaultValue={state.formValues?.etiquetas?.toString() ?? formatTags(hito?.etiquetas)} placeholder="agua, serviu, reunión" />
          </Field>

          <div className="grid gap-4 md:grid-cols-2">
            <CheckField name="destacado" label="Destacado" defaultChecked={state.formValues?.destacado === true || hito?.destacado} />
            <CheckField name="visiblePublico" label="Visible público" defaultChecked={state.formValues?.visiblePublico !== false && hito?.visiblePublico !== false} />
          </div>

          <div className="flex justify-end">
            <Button type="submit" className="min-w-40">
              {submitLabel ?? (mode === "create" ? "Crear hito" : "Guardar cambios")}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

function Field({ label, hint, error, children }: { label: string; hint?: string; error?: string; children: ReactNode }) {
  return (
    <div className="space-y-2">
      <Label>{label}</Label>
      {hint ? <p className="text-xs text-muted-foreground">{hint}</p> : null}
      {children}
      {error ? <p className="text-xs text-destructive">{error}</p> : null}
    </div>
  );
}

function CheckField({ name, label, defaultChecked }: { name: string; label: string; defaultChecked?: boolean }) {
  return (
    <div className="flex items-center gap-3 rounded-lg border border-border bg-muted px-4 py-3">
      <Checkbox id={name} name={name} defaultChecked={defaultChecked} />
      <Label htmlFor={name}>
        {label}
      </Label>
    </div>
  );
}

function dateToInput(value: Date | null | undefined) {
  if (!value) return "";
  const year = value.getFullYear();
  const month = String(value.getMonth() + 1).padStart(2, "0");
  const day = String(value.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
