import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/shared/common/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { useOrganizationAdmins } from "@/super-admin/hooks/useOrganizationAdmins";
import { OrganizationAdminPayload, UnitAdminPayload } from "@/super-admin/services/api/organizationAdminService";
import { useNavigate } from "react-router-dom";
import { t } from "i18next";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useEffect, useState } from "react";
import { useAuth } from "@/shared/context/AuthContext";
import { useUnit } from "@/user-management/hooks/useUnit";

const simplifiedSchema = z.object({
  name: z.object({
    am: z.string().min(1, t("organization.amharicNameRequired")),
    en: z.string().min(1, t("organization.englishNameRequired")),
  }),
  email: z.string().email(t("organization.invalidEmail")),
  username: z.string().min(3, t("organization.usernameMinLength")),
  unitId: z.string().min(1, t("organization.organizationRequired")),
  phone: z
    .string()
    .regex(/^(\+251|0)?9\d{8}$/, t("organization.invalidPhoneNumber")),
});

type SimplifiedFormValues = z.infer<typeof simplifiedSchema>;

export const AdminRegistrationForm = () => {
  const navigate = useNavigate();
  const localizedName = useLocalizedName();

  const { organizationsResponse } = useOrganizations("Org", {
    take: 3000,
  });
  const {  createUnitAdmin, isCreating } = useOrganizationAdmins();
  const { user } = useAuth();


const [selectedOrgId, setSelectedOrgId] = useState<string>("");
 const { data: unitsResponse, isLoading: isLoadingUnits } = useUnit().getList(
   selectedOrgId || "",
   { take: 300, skip: 0 }
 );

  // Add state for selected unitId
  // Default: if super_admin => "All", otherwise wait for units
  const [selectedUnitId, setSelectedUnitId] = useState<string>("All");

  useEffect(() => {
    // If there’s no selectedUnitId yet, default to first unit (if any), otherwise keep "All"
    if (!selectedUnitId) {
      if (unitsResponse?.data?.items?.length) {
        setSelectedUnitId(unitsResponse.data.items[0].id);
      } else {
        setSelectedUnitId("All");
      }
    }
  }, [unitsResponse, selectedUnitId]);

  const form = useForm<SimplifiedFormValues>({
    resolver: zodResolver(simplifiedSchema),
    defaultValues: {
      name: { am: "", en: "" },
      email: "",
      username: "",
      unitId: "",
      phone: "",
    },
  });

  const onSubmit = async (values: SimplifiedFormValues) => {
    const payload: UnitAdminPayload = {
      email: values.email,
      name: values.name,
      unitId: values.unitId,
      username: values.username,
      phoneNumber: values.phone,
    };
    createUnitAdmin({
      payload,
      successCallback: () => {
        navigate("/user-management/organization_admins");
      },
    });
  };

  return (
    <Card className="max-w-2xl mx-auto shadow-md border-gray-200 dark:border-gray-700">
      <CardHeader>
        <CardTitle className="text-xl font-semibold text-gray-800 dark:text-gray-100">
          {t("organization.registerAdminTitle")}
        </CardTitle>
        <CardDescription className="text-gray-500 dark:text-gray-400">
          {t("organization.registerAdminDescription")}
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
          <div className="grid grid-cols-2 gap-6">
            <div className="space-y-2">
              <Label htmlFor="name.en">
                {t("organization.nameEnglish")}{" "}
                <span className="text-red-500">*</span>
              </Label>
              <Input
                id="name.en"
                {...form.register("name.en")}
                placeholder={t("organization.enterEnglishName")}
              />
              {form.formState.errors.name?.en && (
                <p className="text-red-500 text-xs">
                  {form.formState.errors.name.en.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="name.am">
                {t("organization.nameAmharic")}{" "}
                <span className="text-red-500">*</span>
              </Label>
              <Input
                id="name.am"
                {...form.register("name.am")}
                placeholder={t("organization.enterAmharicName")}
              />
              {form.formState.errors.name?.am && (
                <p className="text-red-500 text-xs">
                  {form.formState.errors.name.am.message}
                </p>
              )}
            </div>
          </div>

          <div className="space-y-2">
            <Label htmlFor="email">
              {t("organization.email")} <span className="text-red-500">*</span>
            </Label>
            <Input
              id="email"
              type="email"
              {...form.register("email")}
              placeholder={t("organization.emailExample")}
            />
            {form.formState.errors.email && (
              <p className="text-red-500 text-xs">
                {form.formState.errors.email.message}
              </p>
            )}
          </div>

          <div className="space-y-2">
            <Label htmlFor="username">
              {t("organization.username")}{" "}
              <span className="text-red-500">*</span>
            </Label>
            <Input
              id="username"
              {...form.register("username")}
              placeholder={t("organization.enterUsername")}
            />
            {form.formState.errors.username && (
              <p className="text-red-500 text-xs">
                {form.formState.errors.username.message}
              </p>
            )}
          </div>
          <div className="space-y-2">
            <Label htmlFor="phone">
              {t("organization.phoneNumber")}{" "}
              <span className="text-red-500">*</span>
            </Label>
            <Input
              id="phone"
              type="tel"
              {...form.register("phone")}
              placeholder={t("organization.phoneNumberExample")}
            />
            {form.formState.errors.phone && (
              <p className="text-red-500 text-xs">
                {form.formState.errors.phone.message}
              </p>
            )}
          </div>

          <div className="space-y-2 ">
            <Label htmlFor="organizationId">
              {t("organization.organization")}{" "}
              <span className="text-red-500">*</span>
            </Label>
            <Select
              value={selectedOrgId}
              onValueChange={(val: string) => {
                setSelectedOrgId(val);
                form.setValue("unitId", ""); // reset unit when org changes
              }}>
              <SelectTrigger>
                <SelectValue
                  placeholder={t("organization.selectOrganization")}
                />
              </SelectTrigger>
              <SelectContent>
                {organizationsResponse?.items
                  .filter((org) => org.status === "Active")
                  .map((org) => (
                    <SelectItem key={org.id} value={org.id}>
                      {localizedName(org.name)}
                    </SelectItem>
                  ))}
              </SelectContent>
            </Select>
            {form.formState.errors.unitId && (
              <p className="text-red-500 text-xs">
                {form.formState.errors.unitId.message}
              </p>
            )}
          </div>
          <Select
            value={form.watch("unitId")}
            onValueChange={(val: string) => form.setValue("unitId", val)}
            disabled={!selectedOrgId || isLoadingUnits}>
            <SelectTrigger>
              <SelectValue placeholder={t("organization.selectUnit")} />
            </SelectTrigger>
            <SelectContent>
              {unitsResponse?.data?.items?.map((unit:any) => (
                <SelectItem key={unit.id} value={unit.id}>
                  {localizedName(unit.name)}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          {form.formState.errors.unitId && (
            <p className="text-red-500 text-xs">
              {form.formState.errors.unitId.message}
            </p>
          )}

          <div className="pt-4">
            <Button
              type="submit"
              disabled={isCreating}
              className="bg-primary hover:bg-primary/90 text-primary-foreground">
              {isCreating
                ? t("organization.registering")
                : t("organization.registerAdmin")}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  );
};
