import { MultiSelect } from "@/shared/common/ui/multi-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 { Button } from "@/shared/common/ui/button";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useUserDetail } from "@/record-management/components/hooks/useUserDetail";
import {
  AssignIncomingRecordPayload,
  AssignRecordDto,
  PositionDto,
  PositionHolderDto,
} from "@/record-management/dto/userRecords/usersDto";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { useCreateIncomingRecords } from "@/record-management/components/hooks/useCreateIncomingRecord";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

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

export interface StartAssignRecord {
  id: string;
}

const AssigneIncomingRecord = ({
  isOpen = false,
  record,
  onSuccess,
  onClose,
}: AssignRecordProps) => {
  const form = useForm<{
    receivingDepartments: string[];
    assignedEmployees: string[];
    remarks: string;
  }>({
    defaultValues: {
      receivingDepartments: [],
      assignedEmployees: [],
      remarks: "",
    },
  });

  const { listPositionResponse, listAllDepartmentResponse } = useSettings();
  const { permissionKeys } = useUserDetail();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const localizedName = useLocalizedName();
  // Map your position list to options for MultiSelect
  const positionOptions = Array.isArray(listAllDepartmentResponse)
    ? listAllDepartmentResponse.map((pos: PositionDto) => ({
        label: localizedName(pos.name) || localizedName(pos.name) || "N/A",
        value: pos.id,
      }))
    : [];

  const employeeOptions = Array.isArray(listPositionResponse)
    ? listPositionResponse.flatMap((unit: PositionHolderDto) =>
        unit.employeePositions.map((pos) => ({
          label: localizedName(unit.user?.name) || "Unnamed employee",
          value: pos.id,
          positionId: pos.positionId,
        })),
      )
    : [];

  const {
    assignIncomingRecord,
    isPending,
  } = useCreateIncomingRecords();

  const handleFormSubmit = form.handleSubmit(async (values) => {
    try {
      if (!record?.id) throw new Error("Record id missing");

      const selectedDepartments = values.receivingDepartments;
      const selectedEmployees = values.assignedEmployees;

      const employeePositions = selectedEmployees
        .map((employeeId) => {
          const empIdStr = employeeId.toString();
          const match = employeeOptions.find(
            (emp) => emp.value.toString() === empIdStr,
          );
          if (!match) return null;
          return {
            positionId: match.positionId,
            employeePositionId: empIdStr,
          };
        })
        .filter((pos): pos is NonNullable<typeof pos> => pos !== null);

      if (selectedDepartments.length === 0 && employeePositions.length === 0)
        throw new Error("No departments or employees selected for assignment.");

      const employeePositionIds = employeePositions.map(
        (p) => p.employeePositionId,
      );
      const payload: AssignIncomingRecordPayload = {
        recordBoxId: record.id,
        recordId: record?.record?.id, // ✅ safe access
        employeePositionIds,
        positionIds: selectedDepartments.length > 0 ? selectedDepartments : [],
        comment: values.remarks,
      };

      assignIncomingRecord(payload, {
        onSuccess: () => {
          form.reset();
          onSuccess();
          onClose();
        },
        onError: (error) => {
          handleError(error);
        },
      });
    } catch (err) {
      console.error("Assignment error:", err);
      toast.error(
        err instanceof Error ? err.message : "Failed to Assign a Record",
      );
    }
  });
  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
      <DialogContent className="sm:max-w-[425px] bg-white dark:bg-gray-800 max-h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle>{t("userIncoming.Assign Record")}</DialogTitle>
          <DialogDescription>
            {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.Department")}</FormLabel>
                    <FormControl>
                      <MultiSelect
                        options={positionOptions}
                        onValueChange={field.onChange}
                        value={field.value}
                        placeholder={t("userIncoming.Department") + "..."}
                        variant="default"
                        animation={200}
                        maxCount={5}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="assignedEmployees"
                render={({ field }) => (
                  <FormItem className="space-y-1">
                    <FormLabel>{t("userIncoming.Employees")}</FormLabel>
                    <FormControl>
                      <MultiSelect
                        options={employeeOptions}
                        onValueChange={field.onChange}
                        value={field.value}
                        placeholder={t("userIncoming.Employees") + "..."}
                        variant="default"
                        animation={200}
                        maxCount={5}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              {!permissionKeys.includes("can:dispatchRecords") && (
                <FormField
                  control={form.control}
                  name="remarks"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t("userIncoming.Remark")}</FormLabel>
                      <Textarea
                        rows={4}
                        placeholder={t("userIncoming.Remark") + "..."}
                        {...field}
                      />
                      <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("common.Cancel")}
              </Button>
              <Button type="submit" disabled={isPending}>
                {isPending
                  ? t("userIncoming.Assigning...")
                  : t("userIncoming.Assign")}
              </Button>
            </DialogFooter>
          </form>
        </FormProvider>
      </DialogContent>
    </Dialog>
  );
};

export default AssigneIncomingRecord;
