'use client';

import { useRouter } from 'next/navigation';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { ArrowRight, UserPlus, UserCheck, X } from 'lucide-react';

import { Button } from '@/components/ui/button';
import { PermissionGate } from '@/components/shared/permission-gate';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface InquiryConvertActionsProps {
  portSlug: string;
  inquiry: {
    id: string;
    triageState: string;
    convertedClientId: string | null;
    convertedInterestId: string | null;
  };
}

export function InquiryConvertActions({ portSlug, inquiry }: InquiryConvertActionsProps) {
  const router = useRouter();
  const queryClient = useQueryClient();

  const invalidate = () => {
    queryClient.invalidateQueries({ queryKey: ['inquiries'] });
  };

  const convert = useMutation({
    mutationFn: (target: 'client' | 'interest') =>
      apiFetch<{ data: { clientId: string; interestId: string | null } }>(
        `/api/v1/inquiries/${inquiry.id}/convert`,
        { method: 'POST', body: { target } },
      ),
    onSuccess: (res, target) => {
      invalidate();
      if (target === 'interest' && res.data.interestId) {
        toast.success('Converted to interest.');
        router.push(`/${portSlug}/interests/${res.data.interestId}`);
      } else {
        toast.success('Converted to client.');
        router.push(`/${portSlug}/clients/${res.data.clientId}`);
      }
    },
    onError: (err: unknown) => toastError(err, 'Convert failed'),
  });

  const triage = useMutation({
    mutationFn: (state: 'open' | 'assigned' | 'dismissed') =>
      apiFetch(`/api/v1/inquiries/${inquiry.id}/triage`, { method: 'PATCH', body: { state } }),
    onSuccess: (_d, state) => {
      invalidate();
      toast.success(`Marked ${state}.`);
    },
    onError: (err: unknown) => toastError(err, 'Update failed'),
  });

  const busy = convert.isPending || triage.isPending;
  const alreadyInterest = Boolean(inquiry.convertedInterestId);

  return (
    <PermissionGate resource="inquiries" action="manage">
      <div className="flex flex-wrap items-center gap-2">
        {alreadyInterest ? (
          <Button variant="outline" size="sm" asChild>
            <a href={`/${portSlug}/interests/${inquiry.convertedInterestId}`}>View interest</a>
          </Button>
        ) : (
          <Button size="sm" disabled={busy} onClick={() => convert.mutate('interest')}>
            <ArrowRight className="mr-1.5 h-4 w-4" aria-hidden />
            Convert to interest
          </Button>
        )}

        {inquiry.convertedClientId ? (
          <Button variant="outline" size="sm" asChild>
            <a href={`/${portSlug}/clients/${inquiry.convertedClientId}`}>View client</a>
          </Button>
        ) : (
          <Button
            variant="outline"
            size="sm"
            disabled={busy}
            onClick={() => convert.mutate('client')}
          >
            <UserPlus className="mr-1.5 h-4 w-4" aria-hidden />
            Convert to client
          </Button>
        )}

        {inquiry.triageState === 'open' ? (
          <Button
            variant="ghost"
            size="sm"
            disabled={busy}
            onClick={() => triage.mutate('assigned')}
          >
            <UserCheck className="mr-1.5 h-4 w-4" aria-hidden />
            Assign to me
          </Button>
        ) : null}

        {inquiry.triageState !== 'dismissed' && inquiry.triageState !== 'converted' ? (
          <Button
            variant="ghost"
            size="sm"
            disabled={busy}
            onClick={() => triage.mutate('dismissed')}
          >
            <X className="mr-1.5 h-4 w-4" aria-hidden />
            Dismiss
          </Button>
        ) : null}
      </div>
    </PermissionGate>
  );
}
