'use client';

import { useTransition } from 'react';

import { useRouter } from 'next/navigation';

import { LoaderCircle } from 'lucide-react';

import {
  selectJobAction,
  unselectJobAction,
} from '@kit/doctor/actions/doctor-server-actions';
import { ErrorReason } from '@kit/doctor/schema/error.type';
import { Button, ButtonProps } from '@kit/ui/button';
import { toast } from '@kit/ui/sonner';
import { Trans } from '@kit/ui/trans';
import { cn } from '@kit/ui/utils';

export default function DoctorJobSelect({
  className,
  size = 'sm',
  doctorUserId,
  doctorName,
  analysisOrderId,
  userId,
  isRemovable,
  onJobUpdate,
  linkTo,
}: {
  className?: string;
  size?: ButtonProps['size'];
  doctorUserId?: string | null;
  doctorName?: string;
  analysisOrderId: number;
  userId: string;
  isRemovable?: boolean;
  linkTo?: string;
  onJobUpdate: () => void;
}) {
  const [isPending, startTransition] = useTransition();
  const router = useRouter();

  const handleSelectJob = () => {
    startTransition(async () => {
      const result = await selectJobAction({
        analysisOrderId,
        userId,
      });

      if (result?.success) {
        onJobUpdate();
        linkTo && router.push(linkTo);
      } else {
        toast.error(
          <Trans
            i18nKey={`doctor:error.${result.reason ?? ErrorReason.UNKNOWN}`}
          />,
        );
        if (result.reason === ErrorReason.JOB_ASSIGNED) {
          onJobUpdate();
        }
      }
    });
  };

  const handleUnselectJob = () => {
    startTransition(async () => {
      const result = await unselectJobAction({
        analysisOrderId,
      });

      if (result?.success) {
        onJobUpdate();
      } else {
        toast.error(
          <Trans
            i18nKey={`doctor:error.${result.reason ?? ErrorReason.UNKNOWN}`}
          />,
        );
      }
    });
  };

  if (isRemovable) {
    return (
      <Button
        className={cn('w-16', className)}
        size={size}
        variant="destructive"
        onClick={handleUnselectJob}
        disabled={isPending}
      >
        {isPending ? (
          <LoaderCircle className="h-4 w-4 animate-spin" />
        ) : (
          <Trans i18nKey="doctor:unselectJob" />
        )}
      </Button>
    );
  }

  if (!doctorUserId) {
    return (
      <Button
        className={cn('w-16', className)}
        size={size}
        onClick={handleSelectJob}
        disabled={isPending}
      >
        {isPending ? (
          <LoaderCircle className="h-4 w-4 animate-spin" />
        ) : (
          <Trans i18nKey="doctor:selectJob" />
        )}
      </Button>
    );
  }

  return <>{doctorName}</>;
}
