"use client"

import { use, useCallback, 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 { EditDangerSection } from "@/components/edit-danger-section"
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 {
  deleteAgent,
  fetchAgent,
  updateAgent,
} 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().optional(),
    confirmPassword: z.string().optional(),
    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({ params }: { params: Promise<{ id: string }> }) {
  const { id } = use(params)
  const t = useTranslations("Agents.Create")
  const tEdit = useTranslations("Agents.Edit")
  const tc = useTranslations("Common")
  const router = useRouter()

  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)
  const [saving, setSaving] = useState(false)
  const [deleting, setDeleting] = useState(false)
  const [roles, setRoles] = useState<RoleOption[]>([])
  const [headerName, setHeaderName] = useState("")

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

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const [agent, roleList] = await Promise.all([
        fetchAgent(id),
        fetchRolesList(),
      ])
      setRoles(roleList)
      reset({
        firstName: agent.firstName,
        lastName: agent.lastName,
        email: agent.email,
        password: "",
        confirmPassword: "",
        roleId: String(agent.roleId),
        active: agent.active,
      })
      setHeaderName(
        [agent.firstName, agent.lastName].filter(Boolean).join(" ").trim()
      )
    } catch (e) {
      setError(e instanceof Error ? e : new Error(String(e)))
    } finally {
      setLoading(false)
    }
  }, [id, reset])

  useEffect(() => {
    const timer = setTimeout(() => {
      void load()
    }, 0)
    return () => clearTimeout(timer)
  }, [load])

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

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await deleteAgent(id)
      toast.success(tEdit("toast.deleted"))
      router.back()
    } catch (e) {
      if (e instanceof ApiError) {
        toast.error(e.message)
      } else {
        toast.error(tc("api.errorFallback"))
      }
    } finally {
      setDeleting(false)
    }
  }

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

      <QueryState isLoading={loading} isError={Boolean(error)} error={error}>
        <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 {...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"
                          placeholder={tEdit("placeholders.leaveBlankToKeepCurrent")}
                          {...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>

            <EditDangerSection
              sectionTitle={tEdit("sections.dangerZone")}
              actionTitle={tEdit("danger.deleteTitle")}
              actionDescription={tEdit("danger.deleteDescription")}
              confirmMessage={tEdit("confirm.delete", {
                name: headerName || id,
              })}
              actionLabel={tc("actions.delete")}
              disabled={deleting || loading || saving}
              isPending={deleting}
              onDelete={handleDelete}
            />

            <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={saving}>
                  {tc("actions.saveChanges")}
                </Button>
              </div>
            </div>
          </form>
        </Form>
      </QueryState>
    </div>
  )
}
