import React, { useState } from 'react';

import type { ManualCompetitor } from '../../service/visibility/visibility.interface';
import { removeTrackedCompetitor } from '../../service/visibility/visibility.service';

import Modal from './Modal';

interface ConfirmRemoveCompetitorModalProps {
  open: boolean;
  competitor: ManualCompetitor | null;
  onClose: () => void;
  onRemoved: (competitors: ManualCompetitor[]) => void;
  clientId: string;
  token: string;
  brandId: string;
}

/**
 * Confirm dialog for "Stop tracking" a manually added competitor.
 */
const ConfirmRemoveCompetitorModal = ({
  open,
  competitor,
  onClose,
  onRemoved,
  clientId,
  token,
  brandId,
}: ConfirmRemoveCompetitorModalProps): JSX.Element => {
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleConfirm = async () => {
    if (!competitor) return;
    setSubmitting(true);
    setError(null);
    try {
      const response = await removeTrackedCompetitor(
        clientId,
        token,
        brandId,
        competitor.domain
      );
      onRemoved(response.competitors);
      onClose();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'Failed to remove competitor.'
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Stop tracking this competitor?"
      footer={
        <>
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-50 disabled:opacity-50"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={!competitor || submitting}
            className="rounded-md bg-red-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-red-700 disabled:opacity-60"
          >
            {submitting ? 'Removing...' : 'Stop tracking'}
          </button>
        </>
      }
    >
      <div className="flex flex-col gap-3">
        {error && (
          <div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">
            {error}
          </div>
        )}
        {competitor && (
          <p className="text-sm text-gray-700">
            We&apos;ll stop including{' '}
            <span className="font-semibold">
              {competitor.name || competitor.domain}
            </span>{' '}
            in the weekly leaderboard. You can add it back at any time.
          </p>
        )}
      </div>
    </Modal>
  );
};

export default ConfirmRemoveCompetitorModal;
