'use client';

import { useState, useEffect } from 'react';
import { Modal, ModalBody } from '@/components/ui/Modal';
import Button from '@/components/ui/Button';
import { LexicalField } from '@/lib/cms/LexicalField';
import { LeadFormSettings, DEFAULT_LEAD_FORM_SETTINGS } from '@/types/lead-form';
import styles from '@/app/styles/components/LeadFormSettingsModal.module.css';

interface LeadFormSettingsModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSave: () => void;
}

export default function LeadFormSettingsModal({
  isOpen,
  onClose,
  onSave,
}: LeadFormSettingsModalProps) {
  const [settings, setSettings] = useState<LeadFormSettings>(DEFAULT_LEAD_FORM_SETTINGS);
  const [defaultEmail, setDefaultEmail] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (isOpen) {
      fetchSettings();
    }
  }, [isOpen]);

  const fetchSettings = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch('/api/dealer/settings');
      if (response.ok) {
        const data = await response.json();
        setSettings({ ...DEFAULT_LEAD_FORM_SETTINGS, ...data.leadFormSettings });
        // Store the default contact email for placeholder
        if (data.contactEmail) {
          setDefaultEmail(data.contactEmail);
        }
      } else {
        setError('Failed to load settings');
      }
    } catch {
      setError('Failed to load settings');
    } finally {
      setLoading(false);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    setError(null);
    try {
      const response = await fetch('/api/dealer/settings', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ leadFormSettings: settings }),
      });
      if (!response.ok) {
        const data = await response.json().catch(() => ({}));
        throw new Error(data.error || 'Failed to save settings');
      }
      onSave();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to save settings');
    } finally {
      setSaving(false);
    }
  };

  const footer = (
    <div className={styles.footer}>
      <Button variant="secondary" onClick={onClose} disabled={saving}>
        Cancel
      </Button>
      <Button variant="primary" onClick={handleSave} isLoading={saving}>
        Save Settings
      </Button>
    </div>
  );

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Lead Form Settings" size="wide" footer={footer}>
      <ModalBody>
        {loading ? (
          <div className={styles.loading}>Loading settings...</div>
        ) : (
          <div className={styles.form}>
            {error && <div className={styles.error}>{error}</div>}

            <div className={styles.field}>
              <label className={styles.toggleLabel}>
                <input
                  type="checkbox"
                  checked={settings.leadFormEnabled}
                  onChange={(e) => setSettings({ ...settings, leadFormEnabled: e.target.checked })}
                />
                <span className={styles.toggleText}>Enable contact form on your dealer site</span>
              </label>
              <p className={styles.hint}>
                When disabled, visitors will not see the contact form on your site.
              </p>
            </div>

            <div className={styles.field}>
              <label className={styles.toggleLabel}>
                <input
                  type="checkbox"
                  checked={settings.emailNotificationEnabled}
                  onChange={(e) =>
                    setSettings({ ...settings, emailNotificationEnabled: e.target.checked })
                  }
                />
                <span className={styles.toggleText}>Send me email notifications for new leads</span>
              </label>
              <p className={styles.hint}>
                You will receive an email whenever someone submits the contact form.
              </p>
            </div>

            {settings.emailNotificationEnabled && (
              <div className={styles.field}>
                <label className={styles.label}>Notification Email</label>
                <p className={styles.hint}>
                  Email address where you want to receive lead notifications.
                </p>
                <input
                  type="email"
                  className={styles.input}
                  value={settings.notificationEmail || ''}
                  onChange={(e) =>
                    setSettings({ ...settings, notificationEmail: e.target.value || undefined })
                  }
                  placeholder={defaultEmail || 'your@email.com'}
                />
                {defaultEmail && !settings.notificationEmail && (
                  <p className={styles.hint}>
                    Leave blank to use your default contact email ({defaultEmail})
                  </p>
                )}
              </div>
            )}

            <div className={styles.field}>
              <label className={styles.toggleLabel}>
                <input
                  type="checkbox"
                  checked={settings.autoResponseEnabled}
                  onChange={(e) =>
                    setSettings({ ...settings, autoResponseEnabled: e.target.checked })
                  }
                />
                <span className={styles.toggleText}>Send automatic response to leads</span>
              </label>
              <p className={styles.hint}>
                Automatically send a confirmation email to people who submit the form.
              </p>
            </div>

            {settings.autoResponseEnabled && (
              <div className={styles.field}>
                <label className={styles.label}>Auto-Response Message</label>
                <p className={styles.hint}>
                  This message will be sent to leads after they submit the contact form.
                </p>
                <div className={styles.editorWrapper}>
                  <LexicalField
                    value={settings.autoResponseContent}
                    onChange={(html) => setSettings({ ...settings, autoResponseContent: html })}
                  />
                </div>
              </div>
            )}
          </div>
        )}
      </ModalBody>
    </Modal>
  );
}
