import React, { useState } from 'react';

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

import Modal from './Modal';

interface AddCompetitorModalProps {
  open: boolean;
  onClose: () => void;
  onAdded: (competitors: ManualCompetitor[]) => void;
  clientId: string;
  token: string;
  brandId: string;
}

/**
 * Modal that collects ``domain`` (required) and ``name`` (optional) and
 * POSTs to ``/brands/{id}/tracked-competitors``. The submission is
 * idempotent on the backend.
 */
const AddCompetitorModal = ({
  open,
  onClose,
  onAdded,
  clientId,
  token,
  brandId,
}: AddCompetitorModalProps): JSX.Element => {
  const [domain, setDomain] = useState('');
  const [name, setName] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const reset = () => {
    setDomain('');
    setName('');
    setError(null);
  };

  const handleClose = () => {
    reset();
    onClose();
  };

  const handleSubmit = async () => {
    const trimmed = domain.trim().toLowerCase();
    if (!trimmed) {
      setError('Domain is required.');

      return;
    }
    setSubmitting(true);
    setError(null);
    try {
      const response = await addTrackedCompetitor(clientId, token, brandId, {
        domain: trimmed,
        name: name.trim() || undefined,
      });
      onAdded(response.competitors);
      reset();
      onClose();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'Failed to add competitor.'
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title="Add competitor"
      footer={
        <>
          <button
            type="button"
            onClick={handleClose}
            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={handleSubmit}
            disabled={submitting || !domain.trim()}
            className="rounded-md bg-black px-3 py-1.5 text-sm font-medium text-white hover:bg-gray-800 disabled:opacity-60"
          >
            {submitting ? 'Adding...' : 'Add competitor'}
          </button>
        </>
      }
    >
      <div className="flex flex-col gap-4">
        {error && (
          <div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">
            {error}
          </div>
        )}
        <div className="flex flex-col gap-1">
          <label
            htmlFor="competitor-domain"
            className="text-sm font-medium text-gray-900"
          >
            Domain <span className="text-red-600">*</span>
          </label>
          <input
            id="competitor-domain"
            type="text"
            value={domain}
            onChange={e => setDomain(e.target.value)}
            placeholder="rival.com"
            autoComplete="off"
            className="rounded-md border border-gray-300 px-3 py-1.5 text-sm"
          />
          <p className="text-xs text-gray-500">
            Canonical domain without protocol (e.g. rival.com).
          </p>
        </div>
        <div className="flex flex-col gap-1">
          <label
            htmlFor="competitor-name"
            className="text-sm font-medium text-gray-900"
          >
            Name (optional)
          </label>
          <input
            id="competitor-name"
            type="text"
            value={name}
            onChange={e => setName(e.target.value)}
            placeholder="Display name"
            autoComplete="off"
            className="rounded-md border border-gray-300 px-3 py-1.5 text-sm"
          />
          <p className="text-xs text-gray-500">
            Falls back to the domain when left empty.
          </p>
        </div>
      </div>
    </Modal>
  );
};

export default AddCompetitorModal;
