import { Controller, UseFormReturn, useWatch } from "react-hook-form";
import * as z from "zod";
import {
  Form,
  FormField,
  FormItem,
  FormLabel,
  FormControl,
  FormMessage,
} from "@/shared/common/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Button } from "@/shared/common/ui/button";
import { CommentCard } from "@/record-management/common/WorkflowCommentHistory";
import { cn } from "@/shared/lib/utils";
import { useNavigate } from "react-router-dom";
import { delegationFormSchema } from "./delegationFormSchema";
import { KeyValue } from "@/record-management/types/recordSelectTypes";
import useSettings from "../hooks/useSettings";
import { OrganizationsPositions } from "@/record-management/services/api/departmentService";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { format, isValid, parseISO } from "date-fns";
import { fetchEmployeesByPosition } from "@/record-management/services/api/employeesService";
import { EmployeeByPositionDto } from "@/user-management/dto/employees/employees";
import { useTranslation } from "react-i18next";
import DateField from "@/shared/common/form/fields/DateField";
import DateTimeField from "@/shared/common/form/fields/DateTimeField";
import { useLocalizedName } from "@/shared/common/localizedName";
import {
  FormMultiSelectField,
  FormSingleSelectField,
} from "@/shared/common/form/fields/FormFields";
import React from "react";
import { useUserRecords } from "../hooks/useUserRecords";
import { SingleSelect } from "@/shared/common/ui/single-select";
import {
  useSignatureListWithPresigned,
  useTeetersListWithPresigned,
} from "../hooks/useSignatureAndTeeterWithPresigned";
import { UploadedTeeter } from "../Settings/uploadTeeterandSingature";
import { useAuthUser } from "@/record-management/hooks/useAuthUser";
import { RecordContentOutgoingHistory } from "@/record-management/services/api/userRecordService";
import { previewDelegationPdf } from "@/record-management/services/api/employeePositionService";
import { Eye, Download, Loader2 } from "lucide-react";

type DelegationFormValues = z.infer<typeof delegationFormSchema>;

interface DelegationFormProps {
  formInstance: UseFormReturn<any>;
  onSubmit: (values: DelegationFormValues) => void;
  isEditing?: boolean;
  selectedPositionId?: string;
  selectedPositionName?: { am: string; en: string };
  selectedEmployeeId?: string;
  startDate?: string;
  endDate?: Date | null;
  startAmDate?: string;
  endAmDate?: string;
  internalCC?: string[];
  stampId?: string;
  latestOutgoingHistory?: RecordContentOutgoingHistory;
}

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

const getEmployeePositions = (employee?: EmployeeByPositionDto) =>
  Array.isArray(employee?.employeePositions) ? employee.employeePositions : [];

const getMatchingEmployeePosition = (
  employee: EmployeeByPositionDto,
  positionId?: string,
) =>
  getEmployeePositions(employee).find(
    (employeePosition: any) =>
      employeePosition?.position?.id === positionId ||
      employeePosition?.positionId === positionId,
  ) ?? getEmployeePositions(employee)[0];

export const useLocalized = (lang: string) => {
  return useCallback(
    (name?: { am: string; en: string }) => {
      if (!name) return "";
      return lang.startsWith("am") ? name.am || name.en : name.en || name.am;
    },
    [lang],
  );
};

const DelegationForm = ({
  formInstance,
  onSubmit,
  isEditing,
  selectedPositionId,
  selectedPositionName,
  selectedEmployeeId,
  startDate,
  endDate,
  startAmDate,
  endAmDate,
  internalCC,
  stampId,
  latestOutgoingHistory,
}: DelegationFormProps) => {
  const navigate = useNavigate();
  const form = formInstance;
  const { allDepartmentUnits, listAllDepartmentResponse } = useSettings();
  const [uploadedTeeters, setUploadedTeeters] = useState<UploadedTeeter[]>([]);
  const [selectedTeeterUrl, setSelectedTeeterUrl] = useState<string>("");
  const [uploadedSignatures, setUploadedSignatures] = useState<
    UploadedSignature[]
  >([]);
  const [selectedSignatureUrl, setSelectedSignatureUrl] = useState<string>("");
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const [previewPdfUrl, setPreviewPdfUrl] = useState<string | null>(null);
  const [isLoadingPreview, setIsLoadingPreview] = useState(false);
  const { userDetails } = useAuthUser();
  const employeeId = userDetails?.employee?.[0]?.id ?? "";
  const { data: signatureData } = useSignatureListWithPresigned(employeeId);
  const selectedFormLanguage = useWatch({
    control: form.control,
    name: "language",
    defaultValue: "am",
  });
  const { data: teeterData } = useTeetersListWithPresigned(
    selectedFormLanguage === "am" || selectedFormLanguage === "en"
      ? selectedFormLanguage
      : undefined,
  );
  const localizeName = useLocalized(selectedFormLanguage);
  const departmentsList = useMemo(() => {
    const options = allDepartmentUnits.map((unit: OrganizationsPositions) => ({
      label: localizeName(unit.name),
      value: unit.id && unit.id.trim() !== "" ? unit.id : unit.key || "",
    }));

    const hasSelectedPositionOption =
      !!selectedPositionId &&
      options.some((option) => option.value === selectedPositionId);

    if (
      isEditing &&
      selectedPositionId &&
      selectedPositionName &&
      !hasSelectedPositionOption
    ) {
      options.unshift({
        label: localizeName(selectedPositionName),
        value: selectedPositionId,
      });
    }

    return options;
  }, [
    allDepartmentUnits,
    isEditing,
    localizeName,
    selectedPositionId,
    selectedPositionName,
  ]);

  const [positionEmployeesData, setPositionEmployeesData] = useState<
    EmployeeByPositionDto[]
  >([]);
  const { t } = useTranslation();
  const isPreferredLanguageAmharic = selectedFormLanguage === "am";
  useEffect(() => {
    if (isEditing && internalCC && internalCC.length > 0) {
      form.setValue("internalCC", internalCC);
    }
    if (isEditing && endDate) {
      form.setValue("endDate", endDate);
    }
  }, [isEditing, internalCC, stampId, form, endDate]);

  const watchedPositionId = useWatch({
    control: form.control,
    name: "positionId",
  });
  const watchedEmployeeId = useWatch({
    control: form.control,
    name: "employeeId",
  });
  const selectedPosition = useMemo(
    () =>
      allDepartmentUnits.find((unit: OrganizationsPositions) => {
        const unitValue =
          unit.id && unit.id.trim() !== "" ? unit.id : unit.key || "";
        return unitValue === watchedPositionId;
      }),
    [allDepartmentUnits, watchedPositionId],
  );
  const selectedUser = useMemo(
    () =>
      positionEmployeesData.find((emp: EmployeeByPositionDto) => {
        const matchingEmployeePosition = getMatchingEmployeePosition(
          emp,
          watchedPositionId,
        );
        const employeePositionId = matchingEmployeePosition?.id;
        return (
          employeePositionId === watchedEmployeeId ||
          emp.id === watchedEmployeeId ||
          emp.user?.id === watchedEmployeeId
        );
      }),
    [positionEmployeesData, watchedEmployeeId, watchedPositionId],
  );

  const positionEmployees: KeyValue[] = useMemo(
    () =>
      positionEmployeesData.map((emp: EmployeeByPositionDto) => ({
        label: localizeName(emp.user.name),
        value: emp.id,
        employeePositionId: getMatchingEmployeePosition(emp, watchedPositionId)
          ?.id,
      })),
    [localizeName, positionEmployeesData, watchedPositionId],
  );
  const lastLoadedPositionIdRef = useRef<string | null>(null);
  const initialEditPositionIdRef = useRef<string | undefined>(
    selectedPositionId,
  );
  const initialEditEmployeeIdRef = useRef<string | undefined>(
    selectedEmployeeId,
  );

  useEffect(() => {
    initialEditPositionIdRef.current = selectedPositionId;
  }, [selectedPositionId]);

  useEffect(() => {
    initialEditEmployeeIdRef.current = selectedEmployeeId;
  }, [selectedEmployeeId]);

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

    if (!teetersArray?.length) {
      return;
    }

    setUploadedTeeters(teetersArray);

    if (isEditing && stampId) {
      const matchingTeeter = teetersArray.find((t) => t.id === stampId);
      form.setValue("stampId", stampId);
      setSelectedTeeterUrl(matchingTeeter?.url || "");
      return;
    }

    const match =
      teetersArray.find((t) => t.locale === selectedFormLanguage) ??
      (teetersArray.length === 1 ? teetersArray[0] : null);
    if (match) {
      form.setValue("stampId", match.id);
      setSelectedTeeterUrl(match.url);
    }
  }, [teeterData, form, isEditing, stampId, selectedFormLanguage]);
  useEffect(() => {
    if (!signatureData) {
      return;
    }

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

    if (!currentSignature || !signatureData.presignedSignatureUrl) {
      setUploadedSignatures([]);
      setSelectedSignatureUrl("");
      return;
    }

    const availableSignatures: UploadedSignature[] = [
      {
        id: currentSignature.id,
        url: signatureData.presignedSignatureUrl,
        name: currentSignature.fileInfo?.originalname || "Signature",
      },
    ];

    setUploadedSignatures(availableSignatures);
    form.setValue("signatureId", currentSignature.id);
    setSelectedSignatureUrl(signatureData.presignedSignatureUrl);
  }, [signatureData, form]);

  const selectedStampId = form.watch("stampId");
  const selectedSignatureId = form.watch("signatureId");

  useEffect(() => {
    if (!selectedStampId) {
      setSelectedTeeterUrl("");
      return;
    }

    const selectedStamp = uploadedTeeters.find((t) => t.id === selectedStampId);
    setSelectedTeeterUrl(selectedStamp?.url || "");
  }, [selectedStampId, uploadedTeeters]);

  useEffect(() => {
    if (!selectedSignatureId) {
      setSelectedSignatureUrl("");
      return;
    }

    const selectedSignature = uploadedSignatures.find(
      (s) => s.id === selectedSignatureId,
    );
    setSelectedSignatureUrl(selectedSignature?.url || "");
  }, [selectedSignatureId, uploadedSignatures]);

  useEffect(() => {
    const targetPositionId = initialEditPositionIdRef.current;
    if (!targetPositionId) return;
    if (watchedPositionId === targetPositionId) {
      initialEditPositionIdRef.current = undefined;
      return;
    }

    form.setValue("positionId", targetPositionId, {
      shouldDirty: false,
    });
  }, [form, watchedPositionId]);

  useEffect(() => {
    if (!watchedPositionId) return;
  }, [watchedPositionId, selectedPosition]);

  useEffect(() => {
    if (!watchedEmployeeId && !selectedEmployeeId) return;
  }, [selectedEmployeeId, selectedUser, watchedEmployeeId]);

  useEffect(() => {
    if (!selectedUser || !watchedPositionId) return;

    const resolvedEmployeePositionId = getMatchingEmployeePosition(
      selectedUser,
      watchedPositionId,
    )?.id;

    if (!resolvedEmployeePositionId) return;

    const currentEmployeeValue = form.getValues("employeeId");
    if (currentEmployeeValue === resolvedEmployeePositionId) return;

    form.setValue("employeeId", resolvedEmployeePositionId, {
      shouldDirty: false,
      shouldValidate: true,
    });
    form.clearErrors("employeeId");
  }, [form, selectedUser, watchedPositionId]);

  useEffect(() => {
    if (!watchedPositionId) {
      lastLoadedPositionIdRef.current = null;
      setPositionEmployeesData([]);
      return;
    }
    if (lastLoadedPositionIdRef.current === watchedPositionId) {
      return;
    }

    const loadEmployees = async () => {
      try {
        lastLoadedPositionIdRef.current = watchedPositionId;
        const res = await fetchEmployeesByPosition(watchedPositionId);
        setPositionEmployeesData(res);

        const targetEmployeeId = initialEditEmployeeIdRef.current;
        const selectedEmployee = res.find((emp: EmployeeByPositionDto) => {
          const matchingEmployeePosition = getMatchingEmployeePosition(
            emp,
            watchedPositionId,
          );
          const employeePositionId = matchingEmployeePosition?.id;
          return (
            employeePositionId === watchedEmployeeId ||
            emp.id === watchedEmployeeId ||
            employeePositionId === targetEmployeeId ||
            emp.id === targetEmployeeId ||
            emp.user?.id === targetEmployeeId
          );
        });

        const selectedEmployeePositionId = selectedEmployee
          ? getMatchingEmployeePosition(selectedEmployee, watchedPositionId)?.id
          : undefined;

        if (selectedEmployeePositionId) {
          if (selectedEmployeePositionId !== watchedEmployeeId) {
            form.setValue("employeeId", selectedEmployeePositionId, {
              shouldDirty: false,
              shouldValidate: true,
            });
            form.clearErrors("employeeId");
          }
        }

        if (isEditing && watchedPositionId === selectedPositionId) {
          initialEditEmployeeIdRef.current = undefined;
        }
      } catch (error) {
        console.error("Failed to fetch employees by positionId", error);
        lastLoadedPositionIdRef.current = null;
        setPositionEmployeesData([]);
      }
    };

    loadEmployees();
  }, [
    form,
    isEditing,
    selectedPositionId,
    watchedEmployeeId,
    watchedPositionId,
  ]);

  const handleSubmit = (values: DelegationFormValues) => {
    onSubmit(values);
  };

  const handlePreview = async () => {
    try {
      setIsLoadingPreview(true);
      const formValues = form.getValues();
      
      const startDate = formValues.startDate instanceof Date 
        ? formValues.startDate 
        : new Date(formValues.startDate);
      const endDate = formValues.endDate instanceof Date 
        ? formValues.endDate 
        : new Date(formValues.endDate);

      // Build CC array with proper unitId and positionId
      const departmentUnitByValue = new Map(
        allDepartmentUnits.map((unit) => [
          unit.id && unit.id.trim() !== "" ? unit.id : unit.key || "",
          unit,
        ]),
      );
      
      const internalCCValues =
        formValues.internalCC
          ?.map((selectedId: string) => departmentUnitByValue.get(selectedId))
          .filter((unit: any) => Boolean(unit)) ?? [];

      const payload = {
        delegationDto: {
          employeePositionId: formValues.employeeId,
          from: startDate,
          to: endDate,
        },
        signatureId: formValues.signatureId,
        stampId: formValues.stampId,
        locale: formValues.language,
        cc: internalCCValues.map((c: any) => ({
          unitId: c.unitId!,
          positionId: c.id!,
          type: "internal" as const,
        })),
      };

      const pdfBlob = await previewDelegationPdf(payload);
      const url = URL.createObjectURL(pdfBlob);
      setPreviewPdfUrl(url);
      setIsPreviewOpen(true);
    } catch (error) {
      console.error("Failed to generate preview:", error);
    } finally {
      setIsLoadingPreview(false);
    }
  };

  const handlePositionChange = (
    nextPositionId: string,
    currentPositionId: string | undefined,
    onChange: (value: string) => void,
  ) => {
    if (nextPositionId === currentPositionId) {
      return;
    }

    lastLoadedPositionIdRef.current = null;
    initialEditPositionIdRef.current = undefined;
    initialEditEmployeeIdRef.current = undefined;
    setPositionEmployeesData([]);
    form.setValue("employeeId", "", {
      shouldDirty: true,
      shouldValidate: true,
    });
    onChange(nextPositionId);
  };

  const handleEmployeeChange = (employeePositionId: string) => {
    form.setValue("employeeId", employeePositionId, {
      shouldDirty: true,
      shouldTouch: true,
      shouldValidate: true,
    });
    form.clearErrors("employeeId");
  };

  const formatEnglishDateTime = (rawDate?: string) => {
    if (!rawDate) return "-";

    const parsedDate = parseISO(rawDate);
    if (isValid(parsedDate)) {
      return format(parsedDate, "MMMM do, yyyy h:mm a");
    }

    const fallbackDate = new Date(rawDate);
    return isValid(fallbackDate)
      ? format(fallbackDate, "MMMM do, yyyy h:mm a")
      : rawDate;
  };

  const formatHistoryDateTime = (rawDate?: string) => {
    if (!rawDate) return "-";

    const parsedDate = parseISO(rawDate);
    const dateToFormat = isValid(parsedDate) ? parsedDate : new Date(rawDate);
    if (!isValid(dateToFormat)) return rawDate;

    if (selectedFormLanguage === "am") {
      return new Intl.DateTimeFormat("am-ET", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "numeric",
        minute: "2-digit",
      }).format(dateToFormat);
    }

    return formatEnglishDateTime(rawDate);
  };

  const historyEmployeeName =
    localizeName(
      latestOutgoingHistory?.employeePosition?.employee?.name as
        | { en: string; am: string }
        | undefined,
    ) || "";

  const renderReadOnlyField = (label: string, value: string | undefined) => (
    <FormItem className="w-full">
      <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
        {label}
      </FormLabel>
      <div className="border rounded-md px-3 py-2 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-gray-200">
        {value || "-"}
      </div>
    </FormItem>
  );
  return (
    <div className="container mx-auto px-4 py-6 space-y-6">
      <h1 className="text-xl md:text-2xl font-bold dark:text-gray-100">
        {isEditing
          ? t("delegation.editDelegation")
          : t("delegation.addDelegation")}
      </h1>

      {isEditing && latestOutgoingHistory?.comment && (
        <CommentCard
          createdAt={
            latestOutgoingHistory.createdAt ?? "2026-05-14T06:26:45.274Z"
          }
          comment={latestOutgoingHistory.comment}
          assignerName={
            historyEmployeeName || t("common.unknownUser", "Unknown user")
          }
          variant="secondary"
        />
      )}

      <div className="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-4 md:p-6 border border-gray-100 dark:border-gray-700">
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(handleSubmit)}
            className="space-y-6">
            <FormField
              control={form.control}
              name="language"
              render={({ field }) => (
                <FormItem className="w-full max-w-sm">
                  <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
                    {t("common.language", "Language")}
                  </FormLabel>
                  <FormControl>
                    <Select value={field.value} onValueChange={field.onChange}>
                      <SelectTrigger className="w-full dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600">
                        <SelectValue
                          placeholder={t(
                            "common.selectLanguage",
                            "Select language",
                          )}
                        />
                      </SelectTrigger>
                      <SelectContent className="dark:bg-gray-800 dark:border-gray-600">
                        <SelectItem value="en">English</SelectItem>
                        <SelectItem value="am">Amharic</SelectItem>
                      </SelectContent>
                    </Select>
                  </FormControl>
                  <FormMessage className="text-base text-red-500 mt-1" />
                </FormItem>
              )}
            />
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 md:gap-x-8 md:gap-y-6">
              {isEditing ? (
                <>
                  <FormField
                    control={form.control}
                    name="positionId"
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
                          {t("delegation.delegatedPosition")}
                        </FormLabel>
                        <FormControl>
                          <SingleSelect
                            options={departmentsList}
                            onValueChange={(value) =>
                              handlePositionChange(
                                value,
                                field.value,
                                field.onChange,
                              )
                            }
                            value={field.value ?? ""}
                            placeholder={t(
                              "delegation.selectDelegatedPosition",
                            )}
                          />
                        </FormControl>
                        <FormMessage className="text-base text-red-500 mt-1" />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="employeeId"
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
                          {t("delegation.delegateTo")}
                        </FormLabel>
                        <FormControl>
                          <Select
                            onValueChange={handleEmployeeChange}
                            value={field.value ?? ""}
                            disabled={!watchedPositionId}>
                            <SelectTrigger
                              className={cn(
                                "w-full border rounded-md px-3 py-2 text-base shadow-sm transition dark:text-gray-200",
                                !watchedPositionId
                                  ? "bg-gray-100 dark:bg-gray-700 cursor-not-allowed text-gray-400 dark:text-gray-500"
                                  : "border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary dark:bg-gray-700",
                              )}>
                              <SelectValue
                                placeholder={t("delegation.selectEmployee")}
                                className="text-gray-500 dark:text-gray-400"
                              />
                            </SelectTrigger>
                            <SelectContent className="max-h-60 overflow-y-auto border border-gray-200 dark:border-gray-600 rounded-md shadow-lg bg-white dark:bg-gray-800 z-50">
                              {positionEmployees.length > 0 ? (
                                positionEmployees.map((e) => (
                                  <SelectItem
                                    key={e.employeePositionId}
                                    value={e.employeePositionId ?? e.value}
                                    className="px-3 py-2 text-base hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer dark:text-gray-200">
                                    {e.label}
                                  </SelectItem>
                                ))
                              ) : (
                                <div className="px-4 py-2 text-base text-muted-foreground">
                                  {t("delegation.noEmployeesAvailable")}
                                </div>
                              )}
                            </SelectContent>
                          </Select>
                        </FormControl>
                        <FormMessage className="text-base text-red-500 mt-1" />
                      </FormItem>
                    )}
                  />
                  <DateField
                    name="startDate"
                    label={t("delegation.startDate")}
                    control={form.control}
                    isEthiopian={isPreferredLanguageAmharic}
                  />
                  <DateTimeField
                    name="endDate"
                    label={t("delegation.endDate")}
                    control={form.control}
                    isEthiopian={isPreferredLanguageAmharic}
                    isEditing={isEditing}
                  />
                  {/* cc departments */}
                  <FormMultiSelectField
                    control={form.control}
                    name="internalCC"
                    label={t("addRecord.Internal CC")}
                    options={listAllDepartmentResponse.map(
                      (unit: OrganizationsPositions) => ({
                        label: localizeName(unit.name),
                        value:
                          unit.id && unit.id.trim() !== ""
                            ? unit.id
                            : unit.key || "",
                      }),
                    )}
                    placeholder={t("addRecord.Select Internal CC")}
                    maxCount={5}
                  />
                </>
              ) : (
                <>
                  {/* Position */}
                  <FormField
                    control={form.control}
                    name="positionId"
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
                          {t("delegation.delegatedPosition")}
                        </FormLabel>
                        <FormControl>
                          <SingleSelect
                            options={departmentsList}
                            onValueChange={(value) =>
                              handlePositionChange(
                                value,
                                field.value,
                                field.onChange,
                              )
                            }
                            value={field.value ?? ""}
                            placeholder={t(
                              "delegation.selectDelegatedPosition",
                            )}
                          />
                        </FormControl>
                        <FormMessage className="text-base text-red-500 mt-1" />
                      </FormItem>
                    )}
                  />

                  {/* Employee */}
                  <FormField
                    control={form.control}
                    name="employeeId"
                    render={({ field }) => (
                      <FormItem className="w-full">
                        <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
                          {t("delegation.delegateTo")}
                        </FormLabel>
                        <FormControl>
                          <Select
                            onValueChange={handleEmployeeChange}
                            value={field.value ?? ""}
                            disabled={!form.watch("positionId")}>
                            <SelectTrigger
                              className={cn(
                                "w-full border rounded-md px-3 py-2 text-base shadow-sm transition dark:text-gray-200",
                                !form.watch("positionId")
                                  ? "bg-gray-100 dark:bg-gray-700 cursor-not-allowed text-gray-400 dark:text-gray-500"
                                  : "border-gray-300 dark:border-gray-600 focus:outline-none focus:ring-2 focus:ring-primary focus:border-primary dark:bg-gray-700",
                              )}>
                              <SelectValue
                                placeholder={t("delegation.selectEmployee")}
                                className="text-gray-500 dark:text-gray-400"
                              />
                            </SelectTrigger>
                            <SelectContent className="max-h-60 overflow-y-auto border border-gray-200 dark:border-gray-600 rounded-md shadow-lg bg-white dark:bg-gray-800 z-50">
                              {positionEmployees.length > 0 ? (
                                positionEmployees.map((e) => (
                                  <SelectItem
                                    key={e.employeePositionId}
                                    value={e.employeePositionId ?? e.value}
                                    className="px-3 py-2 text-base hover:bg-gray-100 dark:hover:bg-gray-700 cursor-pointer dark:text-gray-200">
                                    {e.label}
                                  </SelectItem>
                                ))
                              ) : (
                                <div className="px-4 py-2 text-base text-muted-foreground">
                                  {t("delegation.noEmployeesAvailable")}
                                </div>
                              )}
                            </SelectContent>
                          </Select>
                        </FormControl>
                        <FormMessage className="text-base text-red-500 mt-1" />
                      </FormItem>
                    )}
                  />

                  <DateField
                    name="startDate"
                    label={t("delegation.startDate")}
                    control={form.control}
                    isEthiopian={isPreferredLanguageAmharic}
                  />
                  <DateField
                    name="endDate"
                    label={t("delegation.endDate")}
                    control={form.control}
                    isEthiopian={isPreferredLanguageAmharic}
                    minDate={form.watch("startDate")}
                  />
                  {/* cc departments */}
                  <FormMultiSelectField
                    control={form.control}
                    name="internalCC"
                    label={t("addRecord.Internal CC")}
                    options={listAllDepartmentResponse.map(
                      (unit: OrganizationsPositions) => ({
                        label: localizeName(unit.name),
                        value:
                          unit.id && unit.id.trim() !== ""
                            ? unit.id
                            : unit.key || "",
                      }),
                    )}
                    placeholder={t("addRecord.Select Internal CC")}
                    maxCount={5}
                  />
                </>
              )}
              <div className="sm:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-4 md:gap-x-8">
                {uploadedTeeters.length > 0 && (
                  <div>
                    <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200">
                      {t("ApprovalPage.selectTetter")}
                    </FormLabel>
                    <Controller
                      name="stampId"
                      control={form.control}
                      rules={{ required: "Please select a tetter" }}
                      render={({ field, fieldState }) => (
                        <>
                          <Select
                            onValueChange={field.onChange}
                            value={field.value}>
                            <SelectTrigger className="dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600">
                              <SelectValue
                                placeholder={t("ApprovalPage.selectTetter")}
                                className="dark:text-gray-400">
                                {field.value
                                  ? (teeterData?.presignedTeeters?.find(
                                      (t) => t.id === field.value,
                                    )?.name ?? t("ApprovalPage.selectTetter"))
                                  : null}
                              </SelectValue>
                            </SelectTrigger>
                            <SelectContent className="dark:bg-gray-800 dark:border-gray-600">
                              {uploadedTeeters.map((teeter) => (
                                <SelectItem
                                  key={teeter.id}
                                  value={teeter.id}
                                  className="dark:text-gray-200 dark:hover:bg-gray-700">
                                  {teeter.name || "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 dark:border-gray-600 rounded p-2 dark:bg-gray-700">
                              <p className="text-sm font-medium mb-1 dark:text-gray-200">
                                {t("ApprovalPage.selectedStamp")}
                              </p>
                              <div className="relative h-30 w-30">
                                <img
                                  src={selectedTeeterUrl}
                                  alt={t("ApprovalPage.selectedStamp")}
                                  className="h-30 w-30 object-contain"
                                />
                              </div>
                            </div>
                          )}
                        </>
                      )}
                    />
                  </div>
                )}

                <div>
                  <FormLabel className="text-base font-medium text-gray-700 dark:text-gray-200 sm:mb-11">
                    {t("ApprovalPage.selectSignature")}
                  </FormLabel>
                  {uploadedSignatures.length <= 1 ? (
                    <div className="mt-2 border dark:border-gray-600 rounded p-2 dark:bg-gray-700">
                      <p className="text-sm font-medium mb-1 dark:text-gray-200">
                        {t("ApprovalPage.selectedSignature")}
                      </p>
                      <div className="relative h-30 w-30">
                        {selectedSignatureUrl ? (
                          <img
                            src={selectedSignatureUrl}
                            alt={t("ApprovalPage.selectedSignature")}
                            className="h-30 w-30 object-contain"
                          />
                        ) : (
                          <p className="text-sm text-gray-500 dark:text-gray-400">
                            {t(
                              "ApprovalPage.noSignatureFound",
                              "No signature found",
                            )}
                          </p>
                        )}
                      </div>
                    </div>
                  ) : (
                    <Controller
                      name="signatureId"
                      control={form.control}
                      rules={{ required: "Please select a signature" }}
                      render={({ field, fieldState }) => (
                        <>
                          <Select
                            onValueChange={field.onChange}
                            value={field.value}>
                            <SelectTrigger className="dark:bg-gray-700 dark:text-gray-200 dark:border-gray-600">
                              <SelectValue
                                placeholder={t("ApprovalPage.selectSignature")}
                                className="dark:text-gray-400"
                              />
                            </SelectTrigger>
                            <SelectContent className="dark:bg-gray-800 dark:border-gray-600">
                              {uploadedSignatures.map((signature) => (
                                <SelectItem
                                  key={signature.id}
                                  value={signature.id}
                                  className="dark:text-gray-200 dark:hover:bg-gray-700">
                                  {signature.name || "Signature"}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                          {fieldState.error && (
                            <p className="text-sm text-red-500 mt-1">
                              {fieldState.error.message}
                            </p>
                          )}
                          {selectedSignatureUrl && (
                            <div className="mt-2 border dark:border-gray-600 rounded p-2 dark:bg-gray-700">
                              <p className="text-sm font-medium mb-1 dark:text-gray-200">
                                {t("ApprovalPage.selectedSignature")}
                              </p>
                              <div className="relative h-30 w-30">
                                <img
                                  src={selectedSignatureUrl}
                                  alt={t("ApprovalPage.selectedSignature")}
                                  className="h-30 w-30 object-contain"
                                />
                              </div>
                            </div>
                          )}
                        </>
                      )}
                    />
                  )}
                </div>
              </div>
            </div>
            <div className="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => navigate("/record-management/delegation")}
                className="w-full sm:w-auto">
                {t("common.Cancel")}
              </Button>
              <Button
                type="button"
                variant="outline"
                onClick={handlePreview}
                disabled={isLoadingPreview || !form.watch("employeeId") || !form.watch("startDate") || !form.watch("endDate")}
                className="w-full sm:w-auto gap-2">
                <Eye className="h-4 w-4" />
                {t("delegation.preview", "Preview")}
              </Button>
            </div>

            {/* PDF Preview Section */}
            {isPreviewOpen && (
              <div className="bg-white dark:bg-gray-800 shadow-sm rounded-lg p-4 md:p-6 border border-gray-100 dark:border-gray-700 mt-6">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="text-xl font-bold dark:text-gray-100">
                    {t("delegation.previewDelegation", "Delegation Preview")}
                  </h2>
                  <button
                    onClick={() => {
                      setIsPreviewOpen(false);
                      if (previewPdfUrl) {
                        URL.revokeObjectURL(previewPdfUrl);
                        setPreviewPdfUrl(null);
                      }
                    }}
                    className="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
                    <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>

                {isLoadingPreview ? (
                  <div className="flex items-center justify-center h-96">
                    <div className="flex flex-col items-center gap-2">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                      <p className="text-gray-500 dark:text-gray-400">
                        {t("common.loading", "Loading...")}
                      </p>
                    </div>
                  </div>
                ) : previewPdfUrl ? (
                  <>
                    <div className="mb-4 border border-gray-200 dark:border-gray-600 rounded-lg overflow-auto" style={{ height: "calc(100vh - 300px)", minHeight: "600px" }}>
                      <iframe
                        src={previewPdfUrl}
                        className="w-full h-full border-0"
                      />
                    </div>

                    <div className="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-4 border-t dark:border-gray-700">
                      <Button
                        type="button"
                        variant="outline"
                        onClick={() => {
                          const link = document.createElement("a");
                          link.href = previewPdfUrl;
                          link.download = "delegation-preview.pdf";
                          document.body.appendChild(link);
                          link.click();
                          document.body.removeChild(link);
                        }}
                        className="w-full sm:w-auto gap-2"
                      >
                        <Download className="h-4 w-4" />
                        {t("common.download", "Download")}
                      </Button>
                      <Button
                        type="submit"
                        className="w-full sm:w-auto"
                        variant={"addRecordBtn"}
                      >
                        {isEditing ? t("delegation.update") : t("delegation.save")}{" "}
                        {t("delegation.title")}
                      </Button>
                    </div>
                  </>
                ) : (
                  <div className="flex items-center justify-center h-96">
                    <p className="text-gray-500 dark:text-gray-400">
                      {t("common.nothingToDisplay", "Nothing to display")}
                    </p>
                  </div>
                )}
              </div>
            )}
          </form>
        </Form>
      </div>
    </div>
  );
};

export default DelegationForm;
