import { useAssignTasks } from "@/record-management/components/hooks/useAssignTasks";
import { MultiSelect } from "@/shared/common/ui/multi-select";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import { Textarea } from "@/shared/common/ui/textarea";
import { useForm, FormProvider } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button } from "@/shared/common/ui/button";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useUserDetail } from "@/record-management/components/hooks/useUserDetail";
import {
  PositionDto,
  ReAssignRecordPayload,
} from "@/record-management/dto/userRecords/usersDto";
import { toast } from "sonner";
import { useTranslation } from "react-i18next";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { AssignRecordDto } from "@/record-management/dto/IncomingRecords/taskDto";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useRemarkByUnitId } from "@/super-admin/hooks/useRemark";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { useEffect, useMemo, useState } from "react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/shared/common/ui/popover";
import { ChevronsUpDown } from "lucide-react";
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/shared/common/ui/command";
import { Controller } from "react-hook-form";

import {
  useSignatureListWithPresigned,
  useTeetersListWithPresigned,
} from "../../hooks/useSignatureAndTeeterWithPresigned";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { EmployeeWithUnitDto } from "@/user-management/dto/employees/employees";
import { useQueries } from "@tanstack/react-query";
import { getChildIncomingInstances } from "@/record-management/services/api/incomingInstanceService";
import { getNoStampsForLanguageMessage } from "@/record-management/utils/stampMessages";

const assignRecordSchema = z
  .object({
    receivingDepartments: z.array(z.string()),
    assignedEmployees: z.array(z.string()),
    remarks: z.string(),
    selectedRemark: z.string(),
    selectedTeeter: z.string(),
    selectedSignature: z.string(),
  })
  .refine(
    (data) =>
      data.receivingDepartments.length > 0 || data.assignedEmployees.length > 0,
    {
      message: "Either receiver position or employee is required",
      path: ["receivingDepartments"],
    },
  );

interface AssignRecordProps {
  isOpen?: boolean;
  record: AssignRecordDto;
  onSuccess: () => void;
  onClose: () => void;
  isTable?: boolean;
}

const AssigneRecord: React.FC<AssignRecordProps> = ({
  isOpen = false,
  record,
  onSuccess,
  onClose,
  isTable,
}) => {
  const form = useForm<z.infer<typeof assignRecordSchema>>({
    resolver: zodResolver(assignRecordSchema),
    defaultValues: {
      receivingDepartments: [],
      assignedEmployees: [],
      remarks: "",
      selectedRemark: "",
      selectedTeeter: "",
      selectedSignature: "",
    },
  });
  const { userDetails } = useAuthUser();
  const unitId = userDetails?.employee?.[0]?.unitId ?? null;
  const { data } = useUnitConfiguration(unitId as string, {
    enabled: !!unitId,
  });
  const config = data?.data?.items?.[0];
  const [teeters, setTeeters] = useState<any[]>([]);
  const [signatures, setSignatures] = useState<any[]>([]);

  const [teeterUrl, setTeeterUrl] = useState("");
  const [signatureUrl, setSignatureUrl] = useState("");
  const { currentEmployeesResponse, allScopedDepartments } = useSettings();
  const { permissionKeys } = useUserDetail();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const [open, setOpen] = useState(false);
  const { data: remarksData, isLoading: isRemarkLoading } = useRemarkByUnitId(
    unitId as string,
    {
      skip: 0,
      take: 300,
    },
  );

  const selectedTeeter = form.watch("selectedTeeter");
  const selectedSignature = form.watch("selectedSignature");
  // Transform remarks for dropdown
  const remarkOptions = useMemo(
    () =>
      remarksData?.items.map((r: { remark: string; description?: string }) => ({
        label: r.remark, // or `${r.remark} - ${r.description}` if you want
        value: r.remark,
      })) || [],
    [remarksData?.items],
  );

  // Note: We don't auto-set the first remark to give users full control
  const localizedName = useLocalizedName();

  const topLevelIncomingInstances = useMemo(() => {
    const instances = record?.incomingInstances;
    return instances?.length ? instances : [record];
  }, [record]);

  const childIncomingInstanceQueries = useQueries({
    queries: topLevelIncomingInstances.map((instance) => ({
      queryKey: ["child-incoming-instances", instance.id],
      queryFn: () => getChildIncomingInstances(instance.id),
      enabled: isOpen && !!instance.id,
      staleTime: 0,
    })),
  });

  const fetchedChildIncomingInstances = childIncomingInstanceQueries.flatMap(
    (query) => query.data ?? [],
  );

  const assignedSelectionIds = useMemo(() => {
    const positionIds = new Set<string>();
    const employeeIds = new Set<string>();
    const employeePositionIds = new Set<string>();
    const collectInstanceIds = (instance: any) => {
      if (!instance) {
        return;
      }

      if (instance.assigneePositionId) {
        positionIds.add(instance.assigneePositionId);
      }
      if (instance.assigneePosition?.id) {
        positionIds.add(instance.assigneePosition.id);
      }
      if (instance.assigneeId) {
        employeeIds.add(instance.assigneeId);
        employeePositionIds.add(instance.assigneeId);
      }
      if (instance.assignee?.id) {
        employeeIds.add(instance.assignee.id);
        employeePositionIds.add(instance.assignee.id);
      }
      if (instance.assignee?.employee?.id) {
        employeeIds.add(instance.assignee.employee.id);
      }
      if (Array.isArray(instance.children)) {
        instance.children.forEach(collectInstanceIds);
      }
    };

    [...topLevelIncomingInstances, ...fetchedChildIncomingInstances].forEach(
      collectInstanceIds,
    );

    return { positionIds, employeeIds, employeePositionIds };
  }, [fetchedChildIncomingInstances, topLevelIncomingInstances]);

  // Map your position list to options for MultiSelect
  const positionOptions = Array.isArray(allScopedDepartments)
    ? allScopedDepartments
        .filter((pos: PositionDto) => !assignedSelectionIds.positionIds.has(pos.id))
        .map((pos: PositionDto) => ({
          label: localizedName(pos.name) || localizedName(pos.name) || "N/A",
          value: pos.id,
        }))
    : [];

  const employeeOptions = (currentEmployeesResponse?.items ?? []).flatMap(
    (employee: EmployeeWithUnitDto) =>
      (employee.employeePositions ?? [])
        .filter(
          (empPos) =>
            !assignedSelectionIds.employeePositionIds.has(empPos.id) &&
            !assignedSelectionIds.employeeIds.has(employee.id),
        )
        .map((empPos) => ({
          label:
            localizedName(employee.user?.name) ||
            localizedName(employee.name) ||
            "Unnamed employee",
          value: empPos.id,
          employeePositionId: empPos.id,
          positionId: empPos.position?.id ?? "",
        })),
  );

  const { assignRecord, isPending } = useAssignTasks();
  const employeeId = userDetails?.employee?.[0]?.id ?? "";

  const locale: "am" | "en" = record?.preferredLanguage
    ?.toLowerCase()
    .startsWith("am")
    ? "am"
    : "en";
  const { data: teeterData } = useTeetersListWithPresigned(locale);
  const { data: signatureData } = useSignatureListWithPresigned(employeeId);
  const handleFormSubmit = form.handleSubmit(async (values) => {
    try {
      if (!record?.id) {
        throw new Error("Record id missing");
      }

      // ✅ 1. Convert department IDs to positionIds
      const departmentPositions = values.receivingDepartments.flatMap(
        (departmentId: string) => {
          return positionOptions
            .filter((pos) => pos.value === departmentId)
            .map((pos) => ({
              positionId: pos.value,
            }));
        },
      );

      // ✅ 2. Handle selected employees
      const employeePositions = values.assignedEmployees
        .map((employeeId: string) => {
          const empIdStr = employeeId.toString();
          const match = employeeOptions.find(
            (emp) => emp.value.toString() === empIdStr,
          );
          if (!match) return null;

          return {
            positionId: match.positionId,
            employeePositionId: employeeId,
          };
        })
        .filter((pos: any): pos is NonNullable<typeof pos> => pos !== null);

      const positions = [...departmentPositions, ...employeePositions];

      // Use selectedRemark if available, otherwise use manual remarks
      const finalRemarks = (
        values.selectedRemark ||
        values.remarks ||
        ""
      ).trim();

      // Record officer (no dispatch permission) must provide a comment
      if (!permissionKeys.includes("can:dispatchRecords") && !finalRemarks) {
        form.setError("remarks", {
          type: "required",
          message: t("userIncoming.commentRequired", "Comment is required"),
        });
        return;
      }
      const payload: ReAssignRecordPayload = {
        incomingInstanceId: record.id,
        recordId: isTable ? record.record.id : record?.recordId || "",
        comment: finalRemarks,
        positions,

        // ✅ OPTIONAL SAFE ADDITION
        ...(selectedTeeter && { teeterId: selectedTeeter }),
        ...(selectedSignature && { signatureId: selectedSignature }),
      };

      assignRecord(payload, {
        onSuccess: () => {
          form.reset();
          onSuccess();
          onClose();
        },
        onError: (error) => {
          handleError(error);
        },
      });
    } catch (err) {
      console.error("Form submit error:", err);
    }
  });
  useEffect(() => {
    const teeters = teeterData?.presignedTeeters;
    if (!teeters?.length) return;
    setTeeters(teeters);
    const match =
      teeters.find((t) => t.locale === locale) ??
      (teeters.length === 1 ? teeters[0] : null);
    if (match) form.setValue("selectedTeeter", match.id);
  }, [teeterData, locale, form]);

  useEffect(() => {
    const current = signatureData?.items?.find(
      (i) => i.isCurrent && i.uploadedSuccessfully,
    );

    if (current && signatureData?.presignedSignatureUrl) {
      setSignatures([
        {
          id: current.id,
          url: signatureData.presignedSignatureUrl,
        },
      ]);
    }
  }, [signatureData]);
  useEffect(() => {
    const t = teeters.find((x) => x.id === selectedTeeter);
    setTeeterUrl(t?.url || "");
  }, [selectedTeeter, teeters]);

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

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent
        className="
      w-[95vw]
      max-w-[425px]
      max-h-[90vh]
      overflow-y-auto
      rounded-xl
      bg-white
      dark:bg-gray-800
      p-4
      sm:p-6
    ">
        <DialogHeader className="space-y-2 text-left">
          <DialogTitle className="text-lg font-semibold">
            {t("userIncoming.Assign Record")}
          </DialogTitle>

          <DialogDescription className="text-sm leading-relaxed">
            {t("userIncoming.Assign this record to one or more departments")}
          </DialogDescription>
        </DialogHeader>

        <FormProvider {...form}>
          <form onSubmit={handleFormSubmit} className="flex flex-col flex-1 overflow-hidden">
            <div className="flex-1 overflow-y-auto px-4 space-y-4">
            <FormField
              control={form.control}
              name="receivingDepartments"
              render={({ field }) => (
                <FormItem className="space-y-1">
                  <FormLabel>
                    {t("userIncoming.Departments")}{" "}
                    <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <MultiSelect
                      options={positionOptions}
                      onValueChange={field.onChange}
                      value={field.value}
                      placeholder={t("userIncoming.Select department(s)...")}
                      variant="default"
                      animation={200}
                      maxCount={3}
                    />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="assignedEmployees"
              render={({ field }) => (
                <FormItem className="space-y-1">
                  <FormLabel>
                    {t("userIncoming.Employees")}{" "}
                    <span className="text-red-500">*</span>
                  </FormLabel>
                  <FormControl>
                    <MultiSelect
                      options={employeeOptions}
                      value={field.value}
                      onValueChange={field.onChange}
                      placeholder={t("userIncoming.Select employee(s)...")}
                      variant="default"
                      animation={200}
                      maxCount={3}
                    />
                  </FormControl>

                  <FormMessage />
                </FormItem>
              )}
            />

            {!permissionKeys.includes("can:dispatchRecords") && (
              <>
                {/* Predefined Remark */}
                <FormField
                  control={form.control}
                  name="selectedRemark"
                  render={({ field }) => (
                    <FormItem className="space-y-2">
                      <FormLabel>
                        {t("userIncoming.Select Predefined Remark")}
                      </FormLabel>

                      <div className="flex flex-col sm:flex-row gap-2">
                        <Popover open={open} onOpenChange={setOpen}>
                          <PopoverTrigger asChild>
                            <Button
                              variant="outline"
                              role="combobox"
                              disabled={isRemarkLoading}
                              className="
                            w-full
                            justify-between
                            overflow-hidden
                          ">
                              <span className="truncate">
                                {field.value
                                  ? remarkOptions.find(
                                      (o: any) => o.value === field.value,
                                    )?.label
                                  : t("userIncoming.Select a remark...")}
                              </span>

                              <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                            </Button>
                          </PopoverTrigger>

                          <PopoverContent
                            align="start"
                            className="
                          w-[85vw]
                          max-w-[300px]
                          p-0
                          dark:bg-gray-800
                          dark:border-gray-700
                        ">
                            <Command>
                              <CommandInput
                                placeholder={t("userIncoming.searchRemark")}
                              />

                              <CommandList>
                                <CommandEmpty>
                                  {t("userIncoming.noRemark")}
                                </CommandEmpty>

                                <CommandGroup>
                                  {remarkOptions.map((option: any) => (
                                    <CommandItem
                                      key={option.value}
                                      value={option.value}
                                      onSelect={() => {
                                        field.onChange(option.value);
                                        form.setValue("remarks", option.value);
                                        setOpen(false);
                                      }}>
                                      {option.label}
                                    </CommandItem>
                                  ))}
                                </CommandGroup>
                              </CommandList>
                            </Command>
                          </PopoverContent>
                        </Popover>

                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => {
                            field.onChange("");
                            form.setValue("remarks", "");
                          }}
                          disabled={!field.value}
                          className="w-full sm:w-auto">
                          {t("userIncoming.Clear")}
                        </Button>
                      </div>

                      <FormMessage />
                    </FormItem>
                  )}
                />

                {config && config.forwardWithTeeterSignature && (
                  <div className="space-y-4">
                    {/* Stamp */}
                    {teeters.length === 0 && teeterData && (
                      <p className="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>
                    )}
                    {teeters.length > 0 && (
                      <FormField
                        control={form.control}
                        name="selectedTeeter"
                        render={({ field }) => (
                          <FormItem className="space-y-2">
                            <FormLabel>Stamp (optional)</FormLabel>

                            <div className="flex flex-col sm:flex-row gap-2">
                              <FormControl>
                                <Select
                                  onValueChange={field.onChange}
                                  value={field.value}>
                                  <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Select stamp">
                                      {field.value
                                        ? (teeterData?.presignedTeeters?.find(
                                            (t) => t.id === field.value,
                                          )?.name ?? "Select stamp")
                                        : null}
                                    </SelectValue>
                                  </SelectTrigger>

                                  <SelectContent>
                                    {teeters.map((t) => (
                                      <SelectItem key={t.id} value={t.id}>
                                        {t.name || "Stamp"}
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </FormControl>

                              <Button
                                type="button"
                                variant="outline"
                                onClick={() => field.onChange("")}
                                disabled={!field.value}
                                className="w-full sm:w-auto">
                                {t("common.Clear", "Clear")}
                              </Button>
                            </div>

                            {teeterUrl && (
                              <img
                                src={teeterUrl}
                                className="
                              h-20
                              w-20
                              object-contain
                              mt-2
                              rounded-md
                              border
                            "
                              />
                            )}
                          </FormItem>
                        )}
                      />
                    )}

                    {/* Signature */}
                    {signatures.length > 0 && (
                      <FormField
                        control={form.control}
                        name="selectedSignature"
                        render={({ field }) => (
                          <FormItem className="space-y-2">
                            <FormLabel>Signature (optional)</FormLabel>

                            <div className="flex flex-col sm:flex-row gap-2">
                              <FormControl>
                                <Select
                                  onValueChange={field.onChange}
                                  value={field.value}>
                                  <SelectTrigger className="w-full">
                                    <SelectValue placeholder="Select signature" />
                                  </SelectTrigger>

                                  <SelectContent>
                                    {signatures.map((s) => (
                                      <SelectItem key={s.id} value={s.id}>
                                        Signature
                                      </SelectItem>
                                    ))}
                                  </SelectContent>
                                </Select>
                              </FormControl>

                              <Button
                                type="button"
                                variant="outline"
                                onClick={() => field.onChange("")}
                                disabled={!field.value}
                                className="w-full sm:w-auto">
                                {t("common.Clear", "Clear")}
                              </Button>
                            </div>

                            {signatureUrl && (
                              <img
                                src={signatureUrl}
                                className="
                              h-16
                              w-full
                              max-w-[160px]
                              object-contain
                              mt-2
                              rounded-md
                              border
                            "
                              />
                            )}
                          </FormItem>
                        )}
                      />
                    )}
                  </div>
                )}

                {/* Readonly predefined remark */}
                {form.watch("selectedRemark") && (
                  <FormField
                    control={form.control}
                    name="remarks"
                    rules={{
                      validate: (value) =>
                        (typeof value === "string" &&
                          value.trim().length > 0) ||
                        t(
                          "userIncoming.commentRequired",
                          "Comment is required",
                        ),
                    }}
                    render={({ field }) => (
                      <FormItem className="space-y-2">
                        <FormLabel>
                          {t("userIncoming.Comment", "Comment")}
                          <span className="text-red-500 ml-1">*</span>
                        </FormLabel>

                        <FormControl>
                          <Textarea
                            rows={4}
                            {...field}
                            readOnly
                            placeholder={t(
                              "userIncoming.Predefined remark selected...",
                            )}
                            className="
                          resize-none
                          bg-gray-50
                          dark:bg-gray-700
                          cursor-not-allowed
                          dark:text-gray-300
                        "
                          />
                        </FormControl>

                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}

                {/* Manual comment */}
                {!form.watch("selectedRemark") && (
                  <FormField
                    control={form.control}
                    name="remarks"
                    rules={{
                      validate: (value) =>
                        (typeof value === "string" &&
                          value.trim().length > 0) ||
                        t(
                          "userIncoming.commentRequired",
                          "Comment is required",
                        ),
                    }}
                    render={({ field }) => (
                      <FormItem className="space-y-2">
                        <FormLabel>
                          {t("userIncoming.Comment", "Comment")}
                          <span className="text-red-500 ml-1">*</span>
                        </FormLabel>

                        <FormControl>
                          <Textarea
                            rows={4}
                            placeholder={t(
                              "userIncoming.Enter your remarks...",
                            )}
                            {...field}
                            className="
                          resize-none
                          dark:bg-gray-700
                          dark:border-gray-600
                          dark:text-gray-100
                        "
                          />
                        </FormControl>

                        <FormMessage />
                      </FormItem>
                    )}
                  />
                )}
              </>
            )}

            </div>

            <DialogFooter className="border-t border-gray-200 dark:border-gray-700 pt-4 mt-4">
              <Button type="button" variant="outline" onClick={onClose}>
                {t("userIncoming.Cancel")}
              </Button>

              <Button
                type="submit"
                disabled={isPending}
                className="w-full sm:w-auto">
                {isPending
                  ? t("userIncoming.Assigning...")
                  : t("userIncoming.Assign")}
              </Button>
            </DialogFooter>
          </form>
        </FormProvider>
      </DialogContent>
    </Dialog>
  );
};

export default AssigneRecord;
