"use client"

import { use, useCallback, useEffect, useMemo, 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 { PageHeader } from "@/components/page-header"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { StatusSwitchField } from "@/components/status-switch-field"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { ApiError } from "@/lib/api/errors"
import {
  deleteTenant,
  fetchTenant,
  fetchTenantStats,
  permanentDeleteTenantCatalog,
  updateTenant,
  type TenantStatistics,
} from "@/lib/api/tenants"
import { Link, useRouter } from "@/i18n/navigation"
import { AssignPlanDialog } from "@/components/assign-plan-dialog"

const schema = z.object({
  name: z.string().min(1, "Name is required."),
  email: z.string().email("Email is required."),
  domain: z.string().min(3, "Domain is required."),
  cname: z.string().optional(),
  isActive: z.boolean(),
  realStore: z.boolean(),
  devTenant: z.boolean(),
  poweredByMarkatty: z.boolean(),
  advancedOrderActions: z.boolean(),
})

export default function Page({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id: tenantId } = use(params)
  const t = useTranslations("Tenants.Edit")
  const tStats = useTranslations("Tenants.Statistics")
  const tc = useTranslations("Common")
  const router = useRouter()

  const numberFmt = useMemo(() => new Intl.NumberFormat(), [])

  const emptyStats: TenantStatistics = {
    products: 0,
    attributes: 0,
    customers: 0,
    customerGroups: 0,
    categories: 0,
  }

  const [stats, setStats] = useState<TenantStatistics>(emptyStats)
  const [headerName, setHeaderName] = useState("")
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)
  const [saving, setSaving] = useState(false)
  const [deleting, setDeleting] = useState(false)
  const [deletingCatalog, setDeletingCatalog] = useState(false)

  const form = useForm<z.infer<typeof schema>>({
    resolver: zodResolver(schema),
    defaultValues: {
      name: "",
      email: "",
      domain: "",
      cname: "",
      isActive: false,
      realStore: false,
      devTenant: false,
      poweredByMarkatty: false,
      advancedOrderActions: false,
    },
  })
  const { reset } = form

  const load = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const [tenant, s] = await Promise.all([
        fetchTenant(tenantId),
        fetchTenantStats(tenantId),
      ])
      setStats(s)
      reset({
        name: tenant.name,
        email: tenant.email,
        domain: tenant.domain,
        cname: tenant.cname || "",
        isActive: tenant.isActive,
        realStore: tenant.realStore,
        devTenant: tenant.devTenant,
        poweredByMarkatty: tenant.poweredByMarkatty,
        advancedOrderActions: tenant.advancedOrderActions,
      })
      setHeaderName(tenant.name)
    } catch (e) {
      setError(e instanceof Error ? e : new Error(String(e)))
    } finally {
      setLoading(false)
    }
  }, [tenantId, reset])

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

  return (
    <div className="flex flex-col gap-4 md:gap-6 py-4 md:py-6">
      <PageHeader
        title={t("title", { name: headerName || `#${tenantId}` })}
        actions={
          <div className="flex items-center gap-2">
            <AssignPlanDialog
              tenantId={tenantId}
              trigger={<Button variant="default">{tc("actions.assignPlan")}</Button>}
            />
            <Button variant="secondary" asChild>
              <Link href={`/tenants/${tenantId}`}>{tc("actions.view")}</Link>
            </Button>
            <Button variant="outline" type="button" onClick={() => router.back()}>
              {tc("actions.back")}
            </Button>
          </div>
        }
      />

      <QueryState isLoading={loading} isError={Boolean(error)} error={error}>
        <div className="gap-4 grid sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5 px-4 lg:px-6">
          {(
            [
              ["products", stats.products],
              ["attributes", stats.attributes],
              ["customers", stats.customers],
              ["customerGroups", stats.customerGroups],
              ["categories", stats.categories],
            ] as const
          ).map(([key, value]) => (
            <Card key={key}>
              <CardHeader>
                <CardTitle className="font-medium text-sm">{tStats(key)}</CardTitle>
              </CardHeader>
              <CardContent className="font-semibold text-2xl">
                {numberFmt.format(value)}
              </CardContent>
            </Card>
          ))}
        </div>

        <Form {...form}>
          <form
            className="gap-6 grid"
            onSubmit={form.handleSubmit(async (values) => {
              const c = values.cname?.trim() ?? ""
              setSaving(true)
              try {
                await updateTenant(tenantId, {
                  name: values.name.trim(),
                  email: values.email.trim(),
                  domain: values.domain.trim(),
                  cname: c.length > 0 ? c : null,
                  isActive: values.isActive,
                  reliable: values.realStore,
                  isDev: values.devTenant,
                  poweredby: values.poweredByMarkatty,
                  advancedOrderActions: values.advancedOrderActions,
                })
                toast.success(t("toast.updated"))
                router.back()
              } catch (e) {
                if (e instanceof ApiError) {
                  toast.error(e.message)
                } else {
                  toast.error(tc("api.errorFallback"))
                }
              } finally {
                setSaving(false)
              }
            })}
          >
            <FormSection title={t("sections.configuration")}>
              <div className="gap-6 grid">
                <div className="gap-3 grid sm:grid-cols-2 xl:grid-cols-3">
                  <StatusSwitchField
                    control={form.control}
                    name="isActive"
                    label={t("labels.status")}
                    description={t("help.statusOnly")}
                  />
                  <StatusSwitchField
                    control={form.control}
                    name="realStore"
                    label={t("labels.realTenant")}
                    description={t("help.realTenantOnly")}
                  />
                  <StatusSwitchField
                    control={form.control}
                    name="poweredByMarkatty"
                    label={t("labels.poweredByMarkatty")}
                    description={t("help.poweredByMarkattyOnly")}
                  />
                  <StatusSwitchField
                    control={form.control}
                    name="devTenant"
                    label={t("labels.devTenant")}
                    description={t("help.devTenantOnly")}
                  />
                  <StatusSwitchField
                    control={form.control}
                    name="advancedOrderActions"
                    label={t("labels.advancedOrderActions")}
                    description={t("help.advancedOrderActionsOnly")}
                  />
                </div>

                <div className="gap-4 grid md:grid-cols-2">
                  <FormField
                    control={form.control}
                    name="name"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>{t("labels.name")}</FormLabel>
                        <FormControl>
                          <Input placeholder={t("placeholders.name")} {...field} />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />

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

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

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

            <FormSection title={t("sections.dangerZone")}>
              <div className="flex md:flex-row flex-col md:justify-between md:items-center gap-3">
                <div className="gap-1 grid">
                  <div className="font-medium">{t("actions.deleteProductsAndCategories")}</div>
                  <p className="text-muted-foreground text-sm">
                    {t("help.deleteProductsAndCategoriesOnly")}
                  </p>
                </div>
                <Button
                  variant="destructive"
                  type="button"
                  className="cursor-pointer"
                  disabled={deletingCatalog}
                  onClick={async () => {
                    if (!window.confirm(t("confirm.deleteCatalog"))) return
                    setDeletingCatalog(true)
                    try {
                      await permanentDeleteTenantCatalog(tenantId)
                      toast.success(t("toast.catalogDeleted"))
                      const s = await fetchTenantStats(tenantId)
                      setStats(s)
                    } catch (e) {
                      if (e instanceof ApiError) {
                        toast.error(e.message)
                      } else {
                        toast.error(tc("api.errorFallback"))
                      }
                    } finally {
                      setDeletingCatalog(false)
                    }
                  }}
                >
                  {deletingCatalog
                    ? tc("api.deleting")
                    : t("actions.deleteProductsAndCategories")}
                </Button>
              </div>

              <div className="flex md:flex-row flex-col md:justify-between md:items-center gap-3 mt-6 pt-6 border-t">
                <div className="gap-1 grid">
                  <div className="font-medium">{t("actions.deleteTenant")}</div>
                  <p className="text-muted-foreground text-sm">{t("help.deleteTenantOnly")}</p>
                </div>
                <Button
                  variant="destructive"
                  type="button"
                  className="cursor-pointer"
                  disabled={deleting}
                  onClick={async () => {
                    if (!window.confirm(t("actions.confirmDeleteTenant"))) return
                    setDeleting(true)
                    try {
                      await deleteTenant(tenantId)
                      toast.success(t("toast.deleted"))
                      router.back()
                    } catch (e) {
                      if (e instanceof ApiError) {
                        toast.error(e.message)
                      } else {
                        toast.error(tc("api.errorFallback"))
                      }
                    } finally {
                      setDeleting(false)
                    }
                  }}
                >
                  {deleting ? tc("api.deleting") : t("actions.deleteTenant")}
                </Button>
              </div>
            </FormSection>

            <div className="px-4 lg:px-6">
              <div className="flex justify-end items-center gap-2">
                <Button variant="outline" type="button" onClick={() => router.back()}>
                  {tc("actions.cancel")}
                </Button>
                <Button type="submit" disabled={saving}>
                  {saving ? tc("api.saving") : tc("actions.saveChanges")}
                </Button>
              </div>
            </div>
          </form>
        </Form>
      </QueryState>
    </div>
  )
}
