import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller, type FieldErrors } from "react-hook-form";
import { toast } from "sonner";
import { Button } from "@/shared/common/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Switch } from "@/shared/common/ui/switch";
import { Textarea } from "@/shared/common/ui/textarea";
import { useApprovalTasks } from "../../hooks/useApprovalTasks";
import { UploadedTeeter } from "../../Settings/uploadTeeterandSingature";

import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  useSignatureListWithPresigned,
  useTeetersListWithPresigned,
} from "../../hooks/useSignatureAndTeeterWithPresigned";
import { useTranslation } from "react-i18next";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { usePositionPrefixes } from "../../hooks/usePositionPrefixes";
import { useLocalizedName } from "@/shared/common/localizedName";
import i18n from "@/i18n";
import { getNoStampsForLanguageMessage } from "@/record-management/utils/stampMessages";

interface ApproveRecordProps {
  open: boolean;
  onClose: () => void;
  recordId: string;
  onSuccess: () => void;
  recordTypeKey?: string;
  referenceNumber?: string;
  isWithTeamSignature?: boolean;
  preferredLanguage?: string;
}

type ApproveFormValues = {
  reason: string;
  selectedTeeter: string;
  selectedSignature: string;
  positionPrefix?: string;
  isWithTeamSignature: boolean;
};

interface UploadedSignature {
  id: string;
  url: string;
  name?: string;
}

const ApproveRecordModal: React.FC<ApproveRecordProps> = ({
  open,
  onClose,
  recordId,
  onSuccess,
  recordTypeKey = "external",
  referenceNumber,
  isWithTeamSignature: recordIsWithTeamSignature = false,
  preferredLanguage,
}) => {
  const { sendToRo, sendToRoLoading, refetch } = useApprovalTasks();
  const [uploadedTeeters, setUploadedTeeters] = useState<UploadedTeeter[]>([]);
  const [signatures, setSignatures] = useState<UploadedSignature[]>([]);
  const [defaultSignature, setDefaultSignature] = useState<
    string | undefined
  >();
  const [selectedTeeterUrl, setSelectedTeeterUrl] = useState<string>("");
  const [selectedSignatureUrl, setSelectedSignatureUrl] = useState<string>("");
  const teeterRef = useRef<HTMLDivElement>(null);
  const positionPrefixRef = useRef<HTMLDivElement>(null);
  const { t } = useTranslation();
  const effectivePreferredLanguage =
    preferredLanguage === "am" || preferredLanguage === "en"
      ? preferredLanguage
      : preferredLanguage?.toLowerCase().startsWith("am")
        ? "am"
        : preferredLanguage?.toLowerCase().startsWith("en")
          ? "en"
          : i18n.language?.startsWith("am")
            ? "am"
            : "en";
  const { handleError } = useErrorHandler(t);
  const { control, handleSubmit, reset, setValue, watch } =
    useForm<ApproveFormValues>({
      defaultValues: {
        reason: "",
        selectedTeeter: undefined,
        selectedSignature: undefined,
        positionPrefix: undefined,
        isWithTeamSignature: recordIsWithTeamSignature,
      },
    });

  const selectedTeeter = watch("selectedTeeter");
  const selectedSignature = watch("selectedSignature");

  const { userDetails } = useAuthUser();
  const employeeId = userDetails?.employee?.[0]?.id ?? "";
  const unitId = userDetails?.employee?.[0]?.unitId ?? "";
  const positionIdFromMetadata = userDetails?.employee?.[0]?.positions?.[0]?.id;
  const localizedName = useLocalizedName(preferredLanguage);
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const shouldCollaboratorAlwaysSign =
    unitConfigData?.data?.items?.[0]?.shouldCollaboratorAlwaysSign ?? false;
  const canPositionBasedReferenceBeUsedForAllTypes =
    unitConfigData?.data?.items?.[0]
      ?.canPositionBasedReferenceBeUsedForAllTypes ?? false;
  const isInternalMemoRecord = recordTypeKey === "internal_memo";
  const canInternalMemoRequirePositionBasedReferenceNumber =
    unitConfigData?.data?.items?.[0]
      ?.canInternalMemoRequirePositionBasedReferenceNumber ?? false;
  const hasReferenceNumber = Boolean(referenceNumber?.trim());
  const shouldShowPositionPrefixSelector =
    !hasReferenceNumber &&
    (canPositionBasedReferenceBeUsedForAllTypes || isInternalMemoRecord);

  const isPositionPrefixRequired =
    !hasReferenceNumber &&
    isInternalMemoRecord &&
    canInternalMemoRequirePositionBasedReferenceNumber;

  // When shouldCollaboratorAlwaysSign is on, force isWithTeamSignature to true
  useEffect(() => {
    if (shouldCollaboratorAlwaysSign) {
      setValue("isWithTeamSignature", true);
    }
  }, [shouldCollaboratorAlwaysSign, setValue]);

  // Clear position prefix if selector shouldn't be shown
  useEffect(() => {
    if (!shouldShowPositionPrefixSelector) {
      setValue("positionPrefix", "");
    }
  }, [setValue, shouldShowPositionPrefixSelector]);

  const { data: signatureData } = useSignatureListWithPresigned(employeeId);
  const locale: "am" | "en" = (preferredLanguage ?? "")
    .toLowerCase()
    .startsWith("am")
    ? "am"
    : "en";
  const { data: teeterData } = useTeetersListWithPresigned(locale);
  const { data: positionPrefixesData } = usePositionPrefixes(
    unitId,
    recordTypeKey,
    positionIdFromMetadata,
  );

  // Handle Teeter data
  useEffect(() => {
    const teetersArray = Array.isArray(teeterData)
      ? teeterData
      : teeterData?.presignedTeeters;

    if (!teetersArray?.length) return;

    setUploadedTeeters(teetersArray);
    const match =
      teetersArray.find((t) => t.locale === locale) ??
      (teetersArray.length === 1 ? teetersArray[0] : null);
    if (match) {
      setValue("selectedTeeter", match.id);
      setSelectedTeeterUrl(match.url);
    }
  }, [teeterData, setValue, locale]);

  // Handle Signature data
  useEffect(() => {
    if (!signatureData) return;

    const currentItem = signatureData.items?.find(
      (item) => item.isCurrent && item.uploadedSuccessfully,
    );

    if (currentItem && signatureData.presignedSignatureUrl) {
      const validSignatures = [
        {
          id: currentItem.id,
          url: signatureData.presignedSignatureUrl,
          name: currentItem.fileInfo.originalname,
        },
      ];

      setSignatures(validSignatures);
      setDefaultSignature(currentItem.id);
      setValue("selectedSignature", currentItem.id);
      setSelectedSignatureUrl(signatureData.presignedSignatureUrl);
    }
  }, [signatureData, setValue]);

  useEffect(() => {
    if (selectedTeeter) {
      const teeter = uploadedTeeters.find((t) => t.id === selectedTeeter);
      setSelectedTeeterUrl(teeter?.url || "");
    }
  }, [selectedTeeter, uploadedTeeters]);

  useEffect(() => {
    if (selectedSignature) {
      const signature = signatures.find((s) => s.id === selectedSignature);
      setSelectedSignatureUrl(signature?.url || "");
    }
  }, [selectedSignature, signatures]);

  const onError = (errors: FieldErrors<ApproveFormValues>) => {
    if (errors.selectedTeeter) {
      teeterRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "center",
      });
      return;
    }

    if (errors.positionPrefix) {
      positionPrefixRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "center",
      });
    }
  };

  const onSubmit = async (data: ApproveFormValues) => {
    if (!recordId) {
      toast.error("Invalid record ID");
      return;
    }

    if (!data.selectedTeeter) {
      toast.error(t("ApprovalPage.selectStamp"));
      return;
    }

    if (isPositionPrefixRequired && !data.positionPrefix) {
      toast.error(
        t(
          "ApprovalPage.positionPrefixRequired",
          "Reference number selection is required",
        ),
      );
      return;
    }

    try {
      await Promise.all([
        sendToRo({
          id: recordId,
          stampId: data.selectedTeeter || undefined,
          signatureId: data.selectedSignature || defaultSignature,
          note: data.reason ? data.reason : "No Comment/አስተያየት የለም",
          recordPrefixId: data.positionPrefix ? data.positionPrefix : undefined,
          isWithTeamSignature: data.isWithTeamSignature,
        }),
        refetch(),
      ]);
      toast.success(t("msg.approveSuccess"));
      onSuccess();
      handleClose();
    } catch (error) {
      // toast.error(error.message || t("msg.approveFailed"));
      handleError(error);
    }
  };

  const handleClose = () => {
    reset();
    setSelectedTeeterUrl("");
    setSelectedSignatureUrl("");
    onClose();
  };

  const isLoadingData = !teeterData && !signatureData;
  const localizedValue = (name: { en: string; am: string }) => {
    if (effectivePreferredLanguage === "am") {
      return name.am || name.en;
    }
    return name.en || name.am;
  };
  return (
    <Dialog
      open={open}
      onOpenChange={(next) => {
        // Radix only fires this with `false` (close intent). Guarding
        // ensures any phantom fire during the loading→form content swap
        // can't unintentionally close the modal.
        if (next === false) {
          handleClose();
        }
      }}
    >
      <DialogContent aria-describedby={undefined} className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle>{t("ApprovalPage.approveRecord")}</DialogTitle>
        </DialogHeader>

        {isLoadingData ? (
          <p className="flex items-center justify-center py-8">
            {t("common.loading")}
          </p>
        ) : (
          <form
            onSubmit={handleSubmit(onSubmit, onError)}
            className="flex max-h-[calc(85vh-4.5rem)] flex-col"
          >
            <div className="flex-1 space-y-4 overflow-y-auto px-6 py-4">
              <div ref={teeterRef}>
                <label className="block text-sm font-medium">
                  {t("ApprovalPage.selectStamp")}
                </label>
                {uploadedTeeters.length === 0 ? (
                  <p className="mt-2 rounded border border-amber-200 bg-amber-50 p-2 text-sm text-amber-700 dark:border-amber-900 dark:bg-amber-950 dark:text-amber-300">
                    {getNoStampsForLanguageMessage(locale, t)}
                  </p>
                ) : uploadedTeeters.length === 1 ? (
                  <div className="mt-2 border rounded p-2">
                    <p className="text-sm font-medium mb-1">
                      {t("ApprovalPage.yourStamp")}
                    </p>
                    <div className="relative h-24 w-24">
                      {selectedTeeterUrl && (
                        <img
                          src={selectedTeeterUrl}
                          alt={t("ApprovalPage.yourStamp")}
                          className="h-24 w-24 object-contain"
                        />
                      )}
                    </div>
                  </div>
                ) : (
                  <Controller
                    name="selectedTeeter"
                    control={control}
                    rules={{ required: "Please select a stamp" }}
                    render={({ field, fieldState }) => (
                      <>
                        <Select
                          onValueChange={field.onChange}
                          value={field.value}
                        >
                          <SelectTrigger>
                            <SelectValue
                              placeholder={t("ApprovalPage.selectStamp")}
                            >
                              {field.value
                                ? (teeterData?.presignedTeeters?.find(
                                    (t) => t.id === field.value,
                                  )?.name ?? t("ApprovalPage.selectStamp"))
                                : null}
                            </SelectValue>
                          </SelectTrigger>
                          <SelectContent>
                            {uploadedTeeters.map((teeter) => (
                              <SelectItem key={teeter.id} value={teeter.id}>
                                {(() => {
                                  const name = teeter.name as unknown;
                                  if (typeof name === "string") return name;
                                  const localized = name as
                                    | { en?: string; am?: string }
                                    | undefined;
                                  return (
                                    localized?.en || localized?.am || "Teeter"
                                  );
                                })()}
                              </SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                        {fieldState.error && (
                          <p className="text-sm text-red-500 mt-1">
                            {fieldState.error.message}
                          </p>
                        )}
                        {selectedTeeterUrl && (
                          <div className="mt-2 border rounded p-2">
                            <p className="text-sm font-medium mb-1">
                              {t("ApprovalPage.selectedStamp")}
                            </p>
                            <div className="relative h-24 w-24">
                              <img
                                src={selectedTeeterUrl}
                                alt={t("ApprovalPage.selectedStamp")}
                                className="h-24 w-24 object-contain"
                              />
                            </div>
                          </div>
                        )}
                      </>
                    )}
                  />
                )}
              </div>

              {signatures.length > 0 && (
                <div>
                  <label className="block text-sm font-medium">
                    {t("ApprovalPage.signature")}
                  </label>
                  {signatures.length === 1 ? (
                    <div className="mt-2 border rounded p-2">
                      <p className="text-sm font-medium mb-1">
                        {t("ApprovalPage.yourSignature")}
                      </p>
                      <div className="relative h-16 w-48">
                        {selectedSignatureUrl && (
                          <img
                            src={selectedSignatureUrl}
                            alt={t("ApprovalPage.yourSignature")}
                            className="h-24 w-24 object-contain"
                          />
                        )}
                      </div>
                    </div>
                  ) : (
                    <Controller
                      name="selectedSignature"
                      control={control}
                      render={({ field }) => (
                        <>
                          <Select
                            onValueChange={field.onChange}
                            value={field.value}
                          >
                            <SelectTrigger>
                              <SelectValue
                                placeholder={t("ApprovalPage.selectSignature")}
                              />
                            </SelectTrigger>
                            <SelectContent>
                              {signatures.map((signature) => (
                                <SelectItem
                                  key={signature.id}
                                  value={signature.id}
                                >
                                  {signature.name || signature.id}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          {selectedSignatureUrl && (
                            <div className="mt-2 border rounded p-2">
                              <p className="text-sm font-medium mb-1">
                                {t("ApprovalPage.selectedSignature")}
                              </p>
                              <div className="relative h-16 w-48">
                                <img
                                  src={selectedSignatureUrl}
                                  alt={t("ApprovalPage.selectedSignature")}
                                  className="h-24 w-24 object-contain"
                                />
                              </div>
                            </div>
                          )}
                        </>
                      )}
                    />
                  )}
                </div>
              )}

              {hasReferenceNumber && (
                <div>
                  <label className="block text-sm font-medium">
                    {t("viewDetail.referenceNumber", "Reference Number")}
                  </label>
                  <div className="mt-1 rounded-md border bg-slate-50 px-3 py-2 text-sm font-medium text-slate-700">
                    {referenceNumber}
                  </div>
                </div>
              )}

              {shouldShowPositionPrefixSelector &&
              positionPrefixesData?.length ? (
                <div ref={positionPrefixRef}>
                  <label className="block text-sm font-medium">
                    {t("contentManagement.positionPrefixes") ||
                      "Position Prefix"}
                  </label>
                  <div className="flex gap-2 items-end">
                    <div className="flex-1">
                      <Controller
                        name="positionPrefix"
                        control={control}
                        rules={{
                          validate: (value) =>
                            !isPositionPrefixRequired ||
                            Boolean(value) ||
                            t(
                              "ApprovalPage.positionPrefixRequired",
                              "Reference number selection is required",
                            ),
                        }}
                        render={({ field, fieldState }) => (
                          <>
                            <Select
                              onValueChange={field.onChange}
                              value={field.value || ""}
                            >
                              <SelectTrigger>
                                <SelectValue
                                  placeholder={
                                    isInternalMemoRecord
                                      ? t(
                                          "addRecord.Select Position Prefix",
                                          "Select Position Prefix",
                                        )
                                      : t(
                                          "contentManagement.positionPrefixes",
                                        ) || "Select position prefix"
                                  }
                                />
                              </SelectTrigger>
                              <SelectContent>
                                {positionPrefixesData?.map((prefix) => (
                                  <SelectItem key={prefix.id} value={prefix.id}>
                                    {localizedValue(prefix.name)}
                                  </SelectItem>
                                ))}
                              </SelectContent>
                            </Select>
                            {fieldState.error ? (
                              <p className="mt-1 text-sm text-red-500">
                                {fieldState.error.message}
                              </p>
                            ) : (
                              isPositionPrefixRequired && (
                                <p className="mt-1 text-xs text-slate-500">
                                  {t(
                                    "ApprovalPage.positionPrefixRequired",
                                    "Reference number selection is required",
                                  )}
                                </p>
                              )
                            )}
                          </>
                        )}
                      />
                    </div>
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => setValue("positionPrefix", "")}
                      className="h-10 px-3"
                    >
                      {t("common.Cancel") || "Clear"}
                    </Button>
                  </div>
                </div>
              ) : null}

              {recordIsWithTeamSignature && shouldCollaboratorAlwaysSign && (
                <div className="flex items-center gap-4">
                  <label className="text-sm font-medium">
                    {t("addRecord.isTeamSig")}
                  </label>
                  <Controller
                    name="isWithTeamSignature"
                    control={control}
                    render={({ field }) => (
                      <Switch
                        checked={field.value}
                        onCheckedChange={field.onChange}
                      />
                    )}
                  />
                </div>
              )}

              <div>
                <label className="block text-sm font-medium">
                  {t("ApprovalPage.Remark")}
                </label>
                <Controller
                  name="reason"
                  control={control}
                  render={({ field }) => (
                    <Textarea
                      {...field}
                      placeholder={t("ApprovalPage.Remark")}
                      rows={4}
                      className="w-full"
                    />
                  )}
                />
              </div>
            </div>

            <div className="flex justify-end space-x-2 border-t px-6 py-4">
              <Button type="button" variant="outline" onClick={handleClose}>
                {t("common.Cancel")}
              </Button>
              <Button
                type="submit"
                disabled={sendToRoLoading}
                className="bg-primary-800 text-white"
              >
                {sendToRoLoading
                  ? t("ApprovalPage.approving")
                  : t("statusBar.Approve")}
              </Button>
            </div>
          </form>
        )}
      </DialogContent>
    </Dialog>
  );
};

export default ApproveRecordModal;
