import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/shared/common/ui/card";
import { Input } from "@/shared/common/ui/input";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { z } from "zod";
import { useOrganizationTypes } from "@/super-admin/hooks/useOrganizationTypes";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import { useNavigate } from "react-router-dom";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";
import { Switch } from "@/shared/common/ui/switch";
import { t } from "i18next";
import { useLocalizedName } from "@/shared/common/localizedName";

const orgSchema = z.object({
  name: z.object({
    am: z.string().min(1, "Amharic name is required"),
    en: z.string().min(1, "English name is required"),
  }),
  key: z.string().min(1, "Key is required"),
  organizationTypeId: z.string().min(1, "Organization Type is required"),
  parentId: z.string().optional(),
  isGovernmentOrganization: z.boolean(),
});

export type FormValues = z.infer<typeof orgSchema>;

interface OrganizationFormProps {
  onSubmit: (values: FormValues) => void;
  type: "Create" | "Edit";
  isLoading: boolean;
  organizationDetails?: OrganizationDto;
}

const OrganizationForm: React.FC<OrganizationFormProps> = ({
  onSubmit,
  isLoading,
  type,
  organizationDetails,
}) => {
  const fieldClassName =
    "h-10 rounded-md border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary";

  const form = useForm<FormValues>({
    resolver: zodResolver(orgSchema),
    defaultValues: {
      name: { am: "", en: "" },
      key: "",
      organizationTypeId: "",
      parentId: undefined,
      isGovernmentOrganization: true,
    },
  });
  const navigate = useNavigate();
  const localizedName = useLocalizedName();
  const {
    organizationTypesResponse,
    isLoading: isLoadingOrgTypes,
    isError: orgTypesError,
  } = useOrganizationTypes();

  const {
    organizationsResponse,
    isLoading: isLoadingOrgs,
    isError: orgsError,
  } = useOrganizations("Org", {
    take: 1000,
  });

  useEffect(() => {
    const en = form.watch("name.en");

    if (en) {
      const commonNumber = "001"; // Example number
      const generatedKey = `${en || ""}_${commonNumber}`
        .replace(/\s+/g, "_") // Replace spaces with underscores
        .toUpperCase();

      form.setValue("key", generatedKey);
    }
  }, [form.watch("name.en")]);

  useEffect(() => {
    if (organizationDetails) {
      form.reset({
        name: organizationDetails.name,
        key: organizationDetails.key,
        organizationTypeId: organizationDetails.organizationTypeId,
        parentId: organizationDetails.parentId ?? undefined,
        isGovernmentOrganization:
          organizationDetails.isGovernmentOrganization ?? true,
      });
    }
  }, [organizationDetails]);

  return (
    <div className="px-2 md:px-4">
      <Card className="max-w-5xl mx-auto shadow-md border-gray-200 dark:border-gray-700 overflow-hidden">
        <CardHeader className="border-b border-gray-200 dark:border-gray-700 bg-gray-50/70 dark:bg-gray-900/40">
          <CardTitle className="text-xl md:text-2xl font-semibold text-gray-800 dark:text-gray-100">
            {type === "Create"
              ? t("organization.createNew")
              : t("organization.edit")}{" "}
            {t("organization.organizations")}
          </CardTitle>
          <CardDescription className="text-gray-500 dark:text-gray-400">
            {t("organization.enterDetails")}
          </CardDescription>
        </CardHeader>

        <CardContent className="p-4 md:p-8">
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
            <div className="rounded-xl border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900/30 p-4 md:p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
                <div className="space-y-2">
                  <Label htmlFor="name.am">
                    {t("organization.nameAmharic")}{" "}
                    <span className="text-red-500">*</span>
                  </Label>
                  <Input {...form.register("name.am")} className={fieldClassName} />
                  {form.formState.errors.name?.am && (
                    <p className="text-red-500 text-xs mt-1">
                      {form.formState.errors.name.am.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="name.en">
                    {t("organization.nameEnglish")}{" "}
                    <span className="text-red-500">*</span>
                  </Label>
                  <Input {...form.register("name.en")} className={fieldClassName} />
                  {form.formState.errors.name?.en && (
                    <p className="text-red-500 text-xs mt-1">
                      {form.formState.errors.name.en.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="code">
                    {t("organization.key")}
                    <span className="text-red-500">*</span>
                  </Label>
                  <Input
                    {...form.register("key")}
                    disabled={type === "Edit"}
                    readOnly={type === "Edit"}
                    className={fieldClassName}
                  />
                  {form.formState.errors.key && (
                    <p className="text-red-500 text-xs mt-1">
                      {form.formState.errors.key.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="organizationType">
                    {t("organization.organizationType")}{" "}
                    <span className="text-red-500">*</span>
                  </Label>
                  <Select
                    value={form.watch("organizationTypeId")}
                    onValueChange={(val: string) =>
                      form.setValue("organizationTypeId", val)
                    }
                    disabled={isLoadingOrgTypes}
                  >
                    <SelectTrigger className={fieldClassName}>
                      <SelectValue
                        placeholder={
                          isLoadingOrgTypes
                            ? t("organization.loading")
                            : t("organization.selectOrganizationType")
                        }
                      />
                    </SelectTrigger>
                    <SelectContent>
                      {isLoadingOrgTypes ? (
                        <SelectItem value="loading" disabled>
                          {t("organization.loadingOrganizationTypes")}
                        </SelectItem>
                      ) : orgTypesError ? (
                        <SelectItem value="error" disabled>
                          {t("organization.errorLoadingOrganizationTypes")}
                        </SelectItem>
                      ) : organizationTypesResponse?.items?.length ? (
                        organizationTypesResponse.items.map((type) => (
                          <SelectItem key={type.id} value={type.id}>
                            {localizedName(type.name)}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="none" disabled>
                          {t("organization.noOrganizationTypesAvailable")}
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                  {form.formState.errors.organizationTypeId && (
                    <p className="text-red-500 text-xs mt-1">
                      {form.formState.errors.organizationTypeId.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2">
                  <Label htmlFor="organizationType">
                    {t("organization.parentOrganization")}
                  </Label>
                  <Select
                    value={form.watch("parentId")}
                    onValueChange={(val: string) => form.setValue("parentId", val)}
                    disabled={isLoadingOrgs}
                  >
                    <SelectTrigger className={fieldClassName}>
                      <SelectValue
                        placeholder={
                          isLoadingOrgs
                            ? t("organization.loading")
                            : t("organization.selectOrganization")
                        }
                      />
                    </SelectTrigger>
                    <SelectContent>
                      {isLoadingOrgs ? (
                        <SelectItem value="loading" disabled>
                          Loading organization types...
                        </SelectItem>
                      ) : orgsError ? (
                        <SelectItem value="error" disabled>
                          Error loading organization types
                        </SelectItem>
                      ) : organizationsResponse?.items?.length ? (
                        organizationsResponse.items.map((type) => (
                          <SelectItem key={type.id} value={type.id}>
                            {localizedName(type.name)}
                          </SelectItem>
                        ))
                      ) : (
                        <SelectItem value="none" disabled>
                          {t("organization.noOrganization")}
                        </SelectItem>
                      )}
                    </SelectContent>
                  </Select>
                  {form.formState.errors.organizationTypeId && (
                    <p className="text-red-500 text-xs mt-1">
                      {form.formState.errors.organizationTypeId.message}
                    </p>
                  )}
                </div>

                <div className="space-y-2 md:col-span-2 xl:col-span-1">
                  <Label htmlFor="isPublic">
                    {t("organization.isOrganizationPublic")}
                  </Label>
                  <div className="h-10 px-3 rounded-md border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 flex items-center justify-end">
                    <Switch
                      id="isPublic"
                      checked={form.watch("isGovernmentOrganization")}
                      onCheckedChange={(value) =>
                        form.setValue("isGovernmentOrganization", value)
                      }
                    />
                  </div>
                  {form.formState.errors.isGovernmentOrganization && (
                    <p className="text-red-500 text-xs mt-1">
                      {form.formState.errors.isGovernmentOrganization.message}
                    </p>
                  )}
                </div>
              </div>
            </div>

            <div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-3 pt-2">
              <Button
                variant="outline"
                type="button"
                onClick={() => {
                  navigate(-1);
                }}
                className="w-full sm:w-auto"
              >
                {t("common.Cancel")}
              </Button>
              <Button
                type="submit"
                disabled={isLoading}
                className="w-full sm:w-auto bg-primary hover:bg-primary/90 text-primary-foreground"
              >
                {isLoading
                  ? `${type === "Create" ? "Creating" : "Editing"}...`
                  : `${
                      type === "Create" ? t("common.create") : t("common.Edit")
                    } `}
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};

export default OrganizationForm;
