"use client"

import { useEffect, useState } from "react"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { useTranslations } from "next-intl"
import { toast } from "sonner"

import { QueryState } from "@/components/api/query-state"
import { FormSection } from "@/components/form-section"
import { StatusSwitchField } from "@/components/status-switch-field"
import { PageHeader } from "@/components/page-header"
import { Button } from "@/components/ui/button"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { ApiError } from "@/lib/api/errors"
import { createAgent } from "@/lib/api/agents"
import { fetchRolesList, type RoleOption } from "@/lib/api/roles"
import { Link, useRouter } from "@/i18n/navigation"

const schema = z
  .object({
    firstName: z.string().min(1, "First name is required."),
    lastName: z.string().min(1, "Last name is required."),
    email: z.string().email("Enter a valid email."),
    password: z.string().min(6, "Password must be at least 6 characters."),
    confirmPassword: z.string().min(6, "Confirm password."),
    roleId: z.string().min(1, "Role is required."),
    active: z.boolean(),
  })
  .refine((v) => v.password === v.confirmPassword, {
    message: "Passwords do not match.",
    path: ["confirmPassword"],
  })

export default function Page() {
  const t = useTranslations("Agents.Create")
  const tc = useTranslations("Common")
  const router = useRouter()
  const [submitting, setSubmitting] = useState(false)
  const [roles, setRoles] = useState<RoleOption[]>([])
  const [rolesLoading, setRolesLoading] = useState(true)
  const [rolesError, setRolesError] = useState<Error | null>(null)

  const form = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    defaultValues: {
      firstName: "",
      lastName: "",
      email: "",
      password: "",
      confirmPassword: "",
      roleId: "",
      active: true,
    },
  })

  useEffect(() => {
    let cancelled = false
    const loadRoles = async () => {
      setRolesLoading(true)
      setRolesError(null)
      try {
        const list = await fetchRolesList()
        if (cancelled) return
        setRoles(list)
        if (list.length > 0) {
          form.setValue("roleId", list[0].id)
        }
      } catch (e) {
        if (!cancelled) {
          setRolesError(e instanceof Error ? e : new Error(String(e)))
        }
      } finally {
        if (!cancelled) setRolesLoading(false)
      }
    }
    void loadRoles()
    return () => {
      cancelled = true
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps -- load roles once on mount
  }, [])

  const handleSubmit = async (values: z.infer<typeof schema>) => {
    setSubmitting(true)
    try {
      await createAgent({
        firstName: values.firstName.trim(),
        lastName: values.lastName.trim(),
        email: values.email.trim(),
        password: values.password,
        passwordConfirmation: values.confirmPassword,
        roleId: Number(values.roleId),
        active: values.active,
      })
      toast.success(t("toast.created"))
      router.back()
    } catch (e) {
      if (e instanceof ApiError) {
        toast.error(e.message)
      } else {
        toast.error(tc("api.errorFallback"))
      }
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <div className="flex flex-col gap-4 py-4 md:gap-6 md:py-6">
      <PageHeader
        title={t("title")}
        actions={
          <Button variant="outline" type="button" onClick={() => router.back()}>
            {tc("actions.back")}
          </Button>
        }
      />

      <QueryState
        isLoading={rolesLoading}
        isError={Boolean(rolesError)}
        error={rolesError}
      >
        <Form {...form}>
          <form
            className="grid gap-6"
            onSubmit={form.handleSubmit(handleSubmit)}
          >
            <FormSection title={t("sections.general")}>
              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  control={form.control}
                  name="firstName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("labels.firstName")}</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="lastName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("labels.lastName")}</FormLabel>
                      <FormControl>
                        <Input {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="email"
                  render={({ field }) => (
                    <FormItem className="md:col-span-2">
                      <FormLabel>{t("labels.email")}</FormLabel>
                      <FormControl>
                        <Input
                          placeholder={tc("placeholders.agentEmail")}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </FormSection>

            <FormSection title={t("sections.password")}>
              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  control={form.control}
                  name="password"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("labels.newPassword")}</FormLabel>
                      <FormControl>
                        <Input type="password" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="confirmPassword"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("labels.confirmPassword")}</FormLabel>
                      <FormControl>
                        <Input type="password" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </FormSection>

            <FormSection title={t("sections.statusRole")}>
              <div className="grid gap-4 md:grid-cols-2">
                <FormField
                  control={form.control}
                  name="roleId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("labels.role")}</FormLabel>
                      <Select
                        value={field.value}
                        onValueChange={field.onChange}
                        disabled={roles.length === 0}
                      >
                        <FormControl>
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder={t("placeholders.selectRole")} />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {roles.map((role) => (
                            <SelectItem key={role.id} value={role.id}>
                              {role.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <StatusSwitchField
                  control={form.control}
                  name="active"
                  label={t("labels.active")}
                  description={t("help.activeOnly")}
                />
              </div>
            </FormSection>

            <div className="px-4 lg:px-6">
              <div className="flex items-center justify-end gap-2">
                <Button variant="outline" type="button" onClick={() => router.back()}>
                  {tc("actions.cancel")}
                </Button>
                <Button type="submit" disabled={submitting || roles.length === 0}>
                  {t("actions.createAgent")}
                </Button>
              </div>
            </div>
          </form>
        </Form>
      </QueryState>
    </div>
  )
}
