import { useEffect } from "react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { t } from "i18next";
import { useTranslation } from "react-i18next";
import { Loader2 } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Input } from "@/shared/common/ui/input";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useUnit } from "@/user-management/hooks/useUnit";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";
import { OrgAdminUser } from "@/super-admin/hooks/useOrgAdmins";

const adminSchema = z.object({
  name: z.object({
    en: z.string().min(1, t("organization.englishNameRequired")),
    am: z.string().min(1, t("organization.amharicNameRequired")),
  }),
  username: z.string().min(3, t("organization.usernameMinLength")),
  email: z.string().email(t("organization.invalidEmail")),
  phoneNumber: z
    .string()
    .regex(/^(\+251|0)?9\d{8}$/, t("organization.invalidPhoneNumber")),
  organizationId: z.string().min(1, t("organization.organizationRequired")),
  /** required when the org has units (unit admin); empty only when the org
   *  has no units → org admin. Enforced at submit, not in the schema. */
  unitId: z.string().optional(),
});

export type AdminFormValues = z.infer<typeof adminSchema>;

const EMPTY_VALUES: AdminFormValues = {
  name: { en: "", am: "" },
  username: "",
  email: "",
  phoneNumber: "",
  organizationId: "",
  unitId: "",
};

const RequiredMark = () => <span className="text-red-500"> *</span>;

interface AdminFormModalProps {
  isOpen: boolean;
  onClose: () => void;
  /** null → add a new admin; set → edit this admin's profile */
  admin: OrgAdminUser | null;
  /** org whose units feed the unit-admin scope picker */
  organizationId?: string;
  /** server-side error from the last submit, shown inline */
  apiError: string | null;
  onSubmit: (values: AdminFormValues) => void;
  isSubmitting: boolean;
}

/** Add-admin (org or unit scope) / edit-admin-profile modal (one form). */
export default function AdminFormModal({
  isOpen,
  onClose,
  admin,
  organizationId,
  apiError,
  onSubmit,
  isSubmitting,
}: AdminFormModalProps) {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const isEdit = !!admin;

  const form = useForm<AdminFormValues>({
    resolver: zodResolver(adminSchema),
    defaultValues: EMPTY_VALUES,
  });

  const { organizationsResponse } = useOrganizations("Org", { take: 3000 });
  const activeOrgs = (organizationsResponse?.items ?? []).filter(
    (org) => org.status === "Active",
  );

  const selectedOrgId = form.watch("organizationId");
  const { data: unitsResponse, isLoading: isLoadingUnits } =
    useUnit().getList(
      selectedOrgId || "",
      { take: 300, skip: 0 },
      isOpen && !isEdit,
    );
  const units = unitsResponse?.data?.items ?? [];

  useEffect(() => {
    if (isOpen) {
      form.reset(
        admin
          ? {
              ...EMPTY_VALUES,
              name: {
                en: admin.name?.en ?? "",
                am: admin.name?.am ?? "",
              },
              username: admin.username ?? "",
              email: admin.email ?? "",
              phoneNumber: admin.phoneNumber ?? "",
            }
          : { ...EMPTY_VALUES, organizationId: organizationId ?? "" },
      );
    }
  }, [isOpen, admin, organizationId, form]);

  // an org with units gets a unit admin — unit is mandatory then; only a
  // unit-less org falls through to an org admin
  const submit = form.handleSubmit((values) => {
    if (!isEdit && units.length > 0 && !values.unitId) {
      form.setError("unitId", {
        message: t("orgAdmins.form.unitRequired"),
      });
      return;
    }
    onSubmit(values);
  });

  const handleClose = () => {
    if (isSubmitting) return;
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
      <DialogContent className="sm:max-w-[520px]">
        <DialogHeader>
          <DialogTitle>
            {isEdit ? t("orgAdmins.edit.title") : t("orgAdmins.add.title")}
          </DialogTitle>
          <DialogDescription>
            {isEdit
              ? t("orgAdmins.edit.description")
              : t("orgAdmins.add.description")}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={submit} className="space-y-4">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <FormField
                control={form.control}
                name="name.en"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("orgAdmins.form.nameEn")}
                      <RequiredMark />
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("organization.enterEnglishName")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={form.control}
                name="name.am"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("orgAdmins.form.nameAm")}
                      <RequiredMark />
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("organization.enterAmharicName")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <FormField
              control={form.control}
              name="username"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    {t("orgAdmins.form.username")}
                    <RequiredMark />
                  </FormLabel>
                  <FormControl>
                    <Input
                      placeholder={t("organization.enterUsername")}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    {t("orgAdmins.form.email")}
                    <RequiredMark />
                  </FormLabel>
                  <FormControl>
                    <Input
                      type="email"
                      placeholder={t("organization.emailExample")}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="phoneNumber"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    {t("orgAdmins.form.phoneNumber")}
                    <RequiredMark />
                  </FormLabel>
                  <FormControl>
                    <Input
                      type="tel"
                      placeholder={t("organization.phoneNumberExample")}
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {!isEdit && (
              <>
                <FormField
                  control={form.control}
                  name="organizationId"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>
                        {t("organization.organization")}
                        <RequiredMark />
                      </FormLabel>
                      <Select
                        value={field.value}
                        onValueChange={(value) => {
                          field.onChange(value);
                          form.setValue("unitId", ""); // reset unit when org changes
                        }}
                      >
                        <FormControl>
                          <SelectTrigger>
                            <SelectValue
                              placeholder={t(
                                "organization.selectOrganization",
                              )}
                            />
                          </SelectTrigger>
                        </FormControl>
                        <SelectContent>
                          {activeOrgs.map((org) => (
                            <SelectItem key={org.id} value={org.id}>
                              {localizedName(org.name)}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                {(isLoadingUnits || units.length > 0 || !selectedOrgId) && (
                  <FormField
                    control={form.control}
                    name="unitId"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>
                          {t("orgAdmins.form.unit")}
                          <RequiredMark />
                        </FormLabel>
                        <Select
                          value={field.value}
                          onValueChange={field.onChange}
                          disabled={!selectedOrgId || isLoadingUnits}
                        >
                          <FormControl>
                            <SelectTrigger>
                              <SelectValue
                                placeholder={
                                  isLoadingUnits
                                    ? t("orgAdmins.form.loadingUnits")
                                    : t("orgAdmins.form.selectUnit")
                                }
                              />
                            </SelectTrigger>
                          </FormControl>
                          <SelectContent>
                            {units.map((unit: any) => (
                              <SelectItem key={unit.id} value={unit.id}>
                                {localizedName(unit.name)}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
                <p className="text-xs text-muted-foreground">
                  {!isLoadingUnits && selectedOrgId && units.length === 0
                    ? t("orgAdmins.add.noUnitsOrgAdmin")
                    : t("orgAdmins.add.inviteNote")}
                </p>
              </>
            )}

            {apiError && (
              <div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-300">
                {apiError}
              </div>
            )}

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
                disabled={isSubmitting}
              >
                {t("common.cancel")}
              </Button>
              <Button
                type="submit"
                disabled={isSubmitting || (!isEdit && isLoadingUnits)}
              >
                {isSubmitting && (
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                )}
                {isEdit
                  ? t("orgAdmins.edit.submit")
                  : t("orgAdmins.add.submit")}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
