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,
  PositionHolderDto,
} from "@/record-management/dto/userRecords/usersDto";
import { toast } from "sonner";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/shared/common/ui/dialog";
import { useTranslation } from "react-i18next";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/shared/common/ui/form";
import { MultiSelect } from "@/shared/common/ui/multi-select";
import { Textarea } from "@/shared/common/ui/textarea";

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

interface AssignIncomingRecordModalProps {
  isOpen: boolean;
  onSuccess: (assignmentData: AssignmentFormData) => void;
  onClose: () => void;
}

export interface AssignmentFormData {
  receivingDepartments: string[];
  assignedEmployees: string[];
  remarks: string;
}

const AssignIncomingRecordModal = ({
  isOpen,
  onSuccess,
  onClose,
}: AssignIncomingRecordModalProps) => {
  const form = useForm<z.infer<typeof assignmentSchema>>({
    resolver: zodResolver(assignmentSchema),
    defaultValues: {
      receivingDepartments: [],
      assignedEmployees: [],
      remarks: "",
    },
  });

  const { listPositionResponse, listAllDepartmentResponse } = useSettings();
  const { permissionKeys } = useUserDetail();
  const { t } = useTranslation();
  const { handleError } = useErrorHandler(t);
  const localizedName = useLocalizedName();

  const positionOptions = Array.isArray(listAllDepartmentResponse)
    ? listAllDepartmentResponse.map((pos: PositionDto) => ({
        label: 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 handleFormSubmit = form.handleSubmit((values) => {
    try {
      form.reset();
      onSuccess(values);
    } catch (err) {
      console.error("Assignment error:", err);
      toast.error(
        err instanceof Error ? err.message : "Failed to process assignment"
      );
    }
  });

  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")} <span className="text-red-500">*</span>
                    </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")} <span className="text-red-500">*</span>
                    </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">
                {t("userIncoming.Continue")}
              </Button>
            </DialogFooter>
          </form>
        </FormProvider>
      </DialogContent>
    </Dialog>
  );
};

export default AssignIncomingRecordModal;
