import React, { useEffect, useState } from 'react';

import type { PromptResponse } from '../../service/visibility/visibility.interface';
import { regeneratePrompts } from '../../service/visibility/visibility.service';

import Modal from './Modal';

/** Props for {@link RegeneratePromptsModal}. */
interface RegeneratePromptsModalProps {
  open: boolean;
  onClose: () => void;
  /** Called with the freshly generated prompts after the backend confirms. */
  onRegenerated: (prompts: PromptResponse[]) => void;
  clientId: string;
  token: string;
  brandId: string;
}

/**
 * Explains what regeneration does and lets the merchant steer it before
 * rebuilding the tracked prompt set. The backend re-reads the live storefront
 * so the new prompts stay inside the real catalog; the optional guidance and
 * business-type override correct cases the auto-detection got wrong.
 *
 * @param {RegeneratePromptsModalProps} props - Dialog props.
 * @returns {JSX.Element} The modal.
 */
const RegeneratePromptsModal = ({
  open,
  onClose,
  onRegenerated,
  clientId,
  token,
  brandId,
}: RegeneratePromptsModalProps): JSX.Element => {
  const [guidance, setGuidance] = useState('');
  const [businessType, setBusinessType] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) setError(null);
  }, [open]);

  const handleRegenerate = async (): Promise<void> => {
    setSubmitting(true);
    setError(null);
    try {
      const res = await regeneratePrompts(clientId, token, brandId, {
        custom_guidance: guidance.trim() || undefined,
        business_type: businessType.trim() || undefined,
      });
      onRegenerated(res.prompts || []);
      onClose();
    } catch (err) {
      setError(
        err instanceof Error ? err.message : 'Failed to regenerate prompts.'
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Regenerate tracked prompts"
      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={handleRegenerate}
            disabled={submitting}
            className="rounded-md bg-pink-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-pink-700 disabled:opacity-60"
          >
            {submitting ? 'Regenerating...' : 'Regenerate prompts'}
          </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>
        )}
        <p className="rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm text-gray-600">
          We re-read your live website to see what you actually sell, then
          rebuild all 16 prompts so they stay inside your real catalog. This
          replaces the current set and takes up to 1-2 minutes. Your past scan
          history is kept.
        </p>
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="font-medium text-gray-700">
            What do you sell? (optional)
          </span>
          <textarea
            value={guidance}
            onChange={event => setGuidance(event.target.value)}
            rows={3}
            placeholder="List your main product categories, and anything you do NOT sell."
            disabled={submitting}
            className="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-pink-500 focus:outline-none focus:ring-1 focus:ring-pink-500"
          />
          <span className="text-xs text-gray-500">
            Use this if the auto-generated prompts drift off what you really
            sell.
          </span>
        </label>
        <label className="flex flex-col gap-1.5 text-sm">
          <span className="font-medium text-gray-700">
            Business type (optional)
          </span>
          <input
            type="text"
            value={businessType}
            onChange={event => setBusinessType(event.target.value)}
            placeholder="Leave empty to keep current, or e.g. marketplace / brand"
            disabled={submitting}
            className="rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:border-pink-500 focus:outline-none focus:ring-1 focus:ring-pink-500"
          />
          <span className="text-xs text-gray-500">
            A retailer/marketplace competes on where-to-buy prompts; a brand
            competes on product prompts.
          </span>
        </label>
      </div>
    </Modal>
  );
};

export default RegeneratePromptsModal;
