import { useState } from 'react';
import { useT } from '@/lib/i18n/react';
import { Button } from '@/components/ui/primitives/Button';
import { Checkbox } from '@/components/ui/primitives/Checkbox';
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/overlays/Dialog';
import { useMutation } from '@tanstack/react-query';
import { authenticatedFetch } from '@/lib/authenticated-fetch';

type Props = {
  open: boolean;
  onClose: () => void;
  onSuccess: () => void;
};

type EnrollResponse = {
  alreadyEnrolled?: boolean;
};

function parseEnrollError(raw: string): 'already' | 'banned' | 'generic' {
  if (raw.includes('alreadyEnrolled') || raw.includes('already enrolled')) return 'already';
  if (raw.includes('USER_BANNED') || raw.includes('banned')) return 'banned';
  return 'generic';
}

export function EnrollModal({ open, onClose, onSuccess }: Props) {
  const t = useT('affiliate_landing');
  const tCommon = useT('common');
  const [tosChecked, setTosChecked] = useState(false);
  const [errorKind, setErrorKind] = useState<'already' | 'banned' | 'generic' | null>(null);

  const enroll = useMutation({
    mutationFn: async () => {
      const res = await authenticatedFetch('/api/referrals/enroll', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          tosAccepted: true,
          primaryChannel: 'other',
        }),
      });
      const text = await res.text();
      return JSON.parse(text) as { data?: EnrollResponse };
    },
    onSuccess: (result) => {
      if (result.data?.alreadyEnrolled) {
        setErrorKind('already');
        window.setTimeout(() => {
          window.location.href = '/affiliate';
        }, 1500);
        return;
      }
      onSuccess();
      onClose();
    },
    onError: (err: Error) => {
      setErrorKind(parseEnrollError(err.message));
      if (parseEnrollError(err.message) === 'already') {
        window.setTimeout(() => {
          window.location.href = '/affiliate';
        }, 1500);
      }
    },
  });

  const errorMessage =
    errorKind === 'already'
      ? t('enroll_modal_error_already')
      : errorKind === 'banned'
        ? t('enroll_modal_error_banned')
        : errorKind === 'generic'
          ? t('enroll_modal_error')
          : null;

  return (
    <Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
      <DialogContent>
        <DialogTitle>{t('enroll_modal_title')}</DialogTitle>

        <div className="mt-2 mb-5 flex items-start gap-3">
          <Checkbox
            id="tos-checkbox"
            checked={tosChecked}
            onCheckedChange={(checked) => setTosChecked(checked === true)}
            aria-required="true"
          />
          <label htmlFor="tos-checkbox" className="text-text-muted text-sm">
            {t('enroll_modal_tos_prefix')}
            <a
              href="/legal/terms"
              target="_blank"
              rel="noopener noreferrer"
              className="text-brand-primary-600 hover:text-brand-primary-700 underline"
            >
              {t('enroll_modal_tos_link')}
            </a>
          </label>
        </div>

        {errorMessage && (
          <p role="alert" className="text-danger-600 mb-4 text-sm">
            {errorMessage}
          </p>
        )}

        <div className="flex gap-3">
          <Button
            variant="primary"
            size="md"
            disabled={!tosChecked || enroll.isPending}
            loading={enroll.isPending}
            onClick={() => {
              setErrorKind(null);
              enroll.mutate();
            }}
          >
            {enroll.isPending ? t('enroll_modal_submitting') : t('enroll_modal_submit')}
          </Button>
          <Button variant="ghost" size="md" onClick={onClose}>
            {tCommon('cancel')}
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
