"use client"

import { 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 { FormSection } from "@/components/form-section"
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 { ApiError } from "@/lib/api/errors"
import { createTenant } from "@/lib/api/tenants"
import { Link, useRouter } from "@/i18n/navigation"

const schema = z
  .object({
    name: z.string().min(2, "Name is required."),
    email: z.string().email("Enter a valid email."),
    phone: z.string().min(6, "Phone is required."),
    username: z.string().min(3, "Username is required."),
    organizationName: z.string().min(2, "Organization name is required."),
    password: z.string().min(6, "Password must be at least 6 characters."),
    confirmPassword: z.string().min(6, "Confirm your password."),
  })
  .refine((v) => v.password === v.confirmPassword, {
    message: "Passwords do not match.",
    path: ["confirmPassword"],
  })

export default function Page() {
  const t = useTranslations("Tenants.Create")
  const tc = useTranslations("Common")
  const router = useRouter()
  const [submitting, setSubmitting] = useState(false)

  const form = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: "",
      email: "",
      phone: "",
      username: "",
      organizationName: "",
      password: "",
      confirmPassword: "",
    },
  })

  const handleSubmit = async (values: z.infer<typeof schema>) => {
    const u = values.username.trim().toLowerCase()
    setSubmitting(true)
    try {
      await createTenant({
        name: values.organizationName.trim(),
        email: values.email.trim(),
        phone: values.phone.trim(),
        username: u,
        password: values.password,
        domain: `${u}.markatty.com`,
      })
      toast.success(t("toast.created"))
      router.push("/tenants")
    } 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 md:gap-6 py-4 md:py-6">
      <PageHeader
        title={t("title")}
        actions={
          <Button variant="outline" asChild>
            <Link href="/tenants">{tc("actions.back")}</Link>
          </Button>
        }
      />

      <Form {...form}>
        <form
          className="gap-6 grid"
          onSubmit={form.handleSubmit(handleSubmit)}
        >
          <FormSection title={t("sections.details")}>
            <div className="gap-4 grid md:grid-cols-2">
              <FormField
                control={form.control}
                name="name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("labels.fullName")}</FormLabel>
                    <FormControl>
                      <Input placeholder={t("placeholders.fullName")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="phone"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("labels.phone")}</FormLabel>
                    <FormControl>
                      <Input placeholder={t("placeholders.phone")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="email"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("labels.email")}</FormLabel>
                    <FormControl>
                      <Input placeholder={t("placeholders.email")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="username"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("labels.username")}</FormLabel>
                    <FormControl>
                      <Input placeholder={t("placeholders.username")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="organizationName"
                render={({ field }) => (
                  <FormItem className="md:col-span-2">
                    <FormLabel>{t("labels.organizationName")}</FormLabel>
                    <FormControl>
                      <Input placeholder={t("placeholders.organizationName")} {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </FormSection>

          <FormSection title={t("sections.password")}>
            <div className="gap-4 grid md:grid-cols-2">
              <FormField
                control={form.control}
                name="password"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("labels.password")}</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>

          <div className="px-4 lg:px-6">
            <div className="flex justify-end items-center gap-2">
              <Button variant="outline" type="button" asChild>
                <Link href="/tenants">{tc("actions.cancel")}</Link>
              </Button>
              <Button type="submit" disabled={submitting}>
                {submitting ? tc("api.saving") : t("actions.createTenant")}
              </Button>
            </div>
          </div>
        </form>
      </Form>
    </div>
  )
}
