"use client";

import { useActionState, useEffect, useState } from "react";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { SubmitButton } from "@/components/fichas/submit-button";
import { nativeSelectClassName } from "@/components/fichas/form-fields";
import { initialState } from "@/server/actions/action-state";
import { toast } from "sonner";
import type { ActionState } from "@/server/actions/action-state";
import { roleOptions } from "@/lib/user-roles";

type UserFormProps = {
  title: string;
  description?: string;
  action: (state: ActionState, formData: FormData) => Promise<ActionState>;
  submitLabel: string;
  initialValues?: {
    name?: string;
    email?: string;
    role?: string;
    isActive?: boolean;
    password?: string;
    confirmPassword?: string;
  };
  showPassword?: boolean;
};

export function UserForm({
  title,
  description,
  action,
  submitLabel,
  initialValues,
  showPassword = false,
}: UserFormProps) {
  const [state, formAction] = useActionState(action, initialState);
  const textValue = (value: unknown, fallback = "") => (typeof value === "string" ? value : fallback);
  const values = {
    name: textValue(state.formValues?.name, initialValues?.name ?? ""),
    email: textValue(state.formValues?.email, initialValues?.email ?? ""),
    role: textValue(state.formValues?.role, initialValues?.role ?? ""),
    isActive:
      typeof state.formValues?.isActive === "boolean"
        ? state.formValues.isActive
        : initialValues?.isActive ?? true,
    password: textValue(state.formValues?.password, initialValues?.password ?? ""),
    confirmPassword: textValue(state.formValues?.confirmPassword, initialValues?.confirmPassword ?? ""),
  };
  useEffect(() => {
    if (!state.message) return;
    if (state.success) {
      toast.success(state.message);
      return;
    }
    toast.error(state.message);
  }, [state.message, state.success]);

  return (
    <Card className="border-border shadow-sm">
      <CardHeader>
        <CardTitle>{title}</CardTitle>
        {description ? <p className="text-sm text-muted-foreground">{description}</p> : null}
      </CardHeader>
      <CardContent>
        <form key={state.formVersion ?? "initial"} action={formAction} className="space-y-5">
          <div className="grid gap-4 md:grid-cols-2">
            <div className="space-y-2">
              <Label htmlFor="name">Nombre</Label>
              <Input id="name" name="name" defaultValue={values.name} />
              <FieldError messages={state.errors?.name} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="email">Correo</Label>
              <Input id="email" name="email" type="email" defaultValue={values.email} />
              <FieldError messages={state.errors?.email} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="role">Rol</Label>
              <select
                id="role"
                name="role"
                defaultValue={values.role}
                className={nativeSelectClassName}
              >
                <option value="">Seleccione</option>
                {roleOptions.map((role) => (
                  <option key={role.value} value={role.value}>
                    {role.label}
                  </option>
                ))}
              </select>
              <FieldError messages={state.errors?.role} />
            </div>
            <div className="space-y-2">
              <Label htmlFor="isActive">Estado</Label>
              <ActiveCheckbox key={`active-${state.formVersion ?? "initial"}`} defaultChecked={values.isActive} />
              <FieldError messages={state.errors?.isActive} />
            </div>
          </div>

          {showPassword ? (
            <div className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="password">Contraseña</Label>
                <Input id="password" name="password" type="password" autoComplete="new-password" defaultValue={values.password} />
                <FieldError messages={state.errors?.password} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="confirmPassword">Confirmar contraseña</Label>
                <Input
                  id="confirmPassword"
                  name="confirmPassword"
                  type="password"
                  autoComplete="new-password"
                  defaultValue={values.confirmPassword}
                />
                <FieldError messages={state.errors?.confirmPassword} />
              </div>
            </div>
          ) : null}

          <div className="flex justify-end">
            <SubmitButton label={submitLabel} />
          </div>
        </form>
      </CardContent>
    </Card>
  );
}

function FieldError({ messages }: { messages?: string[] }) {
  if (!messages?.length) return null;
  return <p className="text-sm text-destructive">{messages[0]}</p>;
}

function ActiveCheckbox({ defaultChecked }: { defaultChecked: boolean }) {
  const [checked, setChecked] = useState(defaultChecked);

  return (
    <label className="flex h-10 items-center gap-2 rounded-md border border-input bg-background px-3 text-sm text-foreground shadow-sm">
      <input type="hidden" name="isActive" value="false" />
      <input
        id="isActive"
        name="isActive"
        type="checkbox"
        value="true"
        defaultChecked={defaultChecked}
        onChange={(event) => setChecked(event.target.checked)}
        className="h-4 w-4 rounded border-input text-primary focus:ring-ring"
      />
      <span>{checked ? "Activo" : "Inactivo"}</span>
    </label>
  );
}
