import { useAssignTasks } from "@/record-management/components/hooks/useAssignTasks";
import { MultiSelect } from "@/shared/common/ui/multi-select";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  AssignCCPayload,
  PositionDto,
  PositionHolderDto,
} from "@/record-management/dto/userRecords/usersDto";
import { useLocalizedName } from "@/shared/common/localizedName";

import { Button } from "@/shared/common/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import { Textarea } from "@/shared/common/ui/textarea";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm, FormProvider } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { z } from "zod";
import { MemoDto } from "@/record-management/components/hooks/useCCIncomingRecords";
import { useUserDetail } from "@/record-management/components/hooks/useUserDetail";
import { useAuthUser } from "@/shared/hooks/useAuthUser";
import { MeDto } from "@/shared/dto/user/meDto";
import useSettings from "@/record-management/components/hooks/useSettings";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";

const assignCCSchema = z.object({
  receivingDepartments: z.array(z.string()).optional(),
  assignedEmployees: z.array(z.string()).optional(),
  remarks: z.string().min(1, "Comment is required"),
}).refine(
  (data) => (data.receivingDepartments?.length ?? 0) > 0 || (data.assignedEmployees?.length ?? 0) > 0,
  {
    message: "At least one department or employee must be selected",
    path: ["receivingDepartments"],
  }
);

type AssignCCFormData = z.infer<typeof assignCCSchema>;

interface AssignCCRecordProps {
  open: boolean;
  onClose: () => void;
  record: MemoDto;
  refetch: () => void;
}

const AssignCCRecord = ({
  open,
  onClose,
  record,
  refetch,
}: AssignCCRecordProps) => {
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const localizedName = useLocalizedName();
  const { userDetails } = useAuthUser();
  const unitId = userDetails?.employee?.[0]?.unitId ?? null;

  const { listPositionResponse, allDepartmentUnits, allScopedDepartments } =
    useSettings();
  const { permissionKeys } = useUserDetail();

  const form = useForm<AssignCCFormData>({
    resolver: zodResolver(assignCCSchema),
    defaultValues: {
      receivingDepartments: [],
      assignedEmployees: [],
      remarks: "",
    },
  });

  // Map your position list to options for MultiSelect
  const positionOptions = Array.isArray(allScopedDepartments)
    ? allScopedDepartments.map((pos: PositionDto) => ({
        label: localizedName(pos.name) || localizedName(pos.name) || "N/A",
        value: pos.id,
      }))
    : [];
  const positionOptions1 = Array.isArray(allScopedDepartments)
    ? allScopedDepartments.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: any) => ({
          label: localizedName(unit.user?.name) || "Unnamed employee",
          value: pos.id,
          positionId: pos.positionId,
        })),
      )
    : [];

  const { assignCC, isAssignCCPending, isAssignCCError, assignCCError } =
    useAssignTasks();

  const handleFormSubmit = form.handleSubmit(async (values) => {
    try {
      const finalRemarks = values.remarks || "";

      // Build positions array from employees only
      // Note: We only use employees since we need both positionId and employeePositionId
      const positions: { positionId: string; employeePositionId: string }[] =
        [];

      // Add positions from selected employees
      if (values.assignedEmployees) {
        values.assignedEmployees.forEach((empId) => {
          const employee = employeeOptions.find((emp) => emp.value === empId);
          if (employee?.positionId) {
            positions.push({
              positionId: employee.positionId, // The position/department ID
              employeePositionId: empId, // The employee's specific position assignment ID
            });
          }
        });
      }

      // Add positions from departments (find employees in those departments)
      if (values.receivingDepartments) {
        values.receivingDepartments.forEach((deptId) => {
          // Find employees in this department
          const employeesInDept = employeeOptions.filter(
            (emp) => emp.positionId === deptId,
          );

          // Add all employees in this department
          employeesInDept.forEach((employee) => {
            // Avoid duplicates
            const alreadyAdded = positions.some(
              (pos) => pos.employeePositionId === employee.value,
            );
            if (!alreadyAdded) {
              positions.push({
                positionId: deptId, // The department/position ID
                employeePositionId: employee.value, // The employee's specific position assignment ID
              });
            }
          });
        });
      }

      // Validate that we have positions to assign
      if (positions.length === 0) {
        toast.error(
          "Please select at least one employee or department with employees",
        );
        return;
      }

      // Get the CC record ID from the content[0].ccs array
      // The structure is: record.content[0].ccs[0].id
      const ccRecordId = record.content?.[0]?.ccs?.[0]?.id;

      if (!ccRecordId) {
        console.error(
          "CC record ID not found in content[0].ccs array. Record:",
          record,
        );
        toast.error("CC record ID not found in content[0].ccs array");
        return;
      }

      const payload: AssignCCPayload = {
        recordCCId: ccRecordId, // Use the CC record ID from content[0].ccs[0].id (e.g., "597e72f7-6c9b-48cd-a9fe-46536f42306a")
        recordId: record.id, // The main record ID (e.g., "14b2c17e-59a1-48e0-bfd6-d89e467d4c39")
        comment: finalRemarks,
        positions,
      };

      assignCC(payload, {
        onSuccess: () => {
          toast.success(t("userIncoming.successassign"));
          form.reset();
          refetch();
          onClose();
        },
        onError: (error) => {
          handleError(error);
        },
      });
    } catch (error) {
      console.error("Form submission error:", error);
      toast.error(t("userIncoming.An error occurred during assignment."));
    }
  });

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="sm:max-w-[425px] bg-white">
        <DialogHeader>
          <DialogTitle>{t("userIncoming.Assign CC Record")}</DialogTitle>
          <DialogDescription>
            {t("userIncoming.Assign this CC record to one or more departments")}
          </DialogDescription>
        </DialogHeader>

        <FormProvider {...form}>
          <form onSubmit={handleFormSubmit} className="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={5}
                    />
                  </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} // string[] of employeeIds
                      onValueChange={field.onChange} // directly writes string[]
                      placeholder={t("userIncoming.Select employee(s)...")}
                      variant="default"
                      animation={200}
                      maxCount={5}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="remarks"
              render={({ field }) => (
                <FormItem className="space-y-1">
                  <FormLabel>{t("userIncoming.Remark")}</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder={t("userIncoming.Enter your remarks...")}
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {isAssignCCError && assignCCError && (
              <p className="text-sm text-red-600">
                {assignCCError instanceof Error
                  ? assignCCError.message
                  : t("userIncoming.An error occurred during assignment.")}
              </p>
            )}

            <DialogFooter>
              <Button type="button" variant="outline" onClick={onClose}>
                {t("userIncoming.Cancel")}
              </Button>
              <Button type="submit" disabled={isAssignCCPending}>
                {isAssignCCPending
                  ? t("userIncoming.Assigning...")
                  : t("userIncoming.Assign CC")}
              </Button>
            </DialogFooter>
          </form>
        </FormProvider>
      </DialogContent>
    </Dialog>
  );
};

export default AssignCCRecord;
