'use client';

import React, { useState, useEffect } from 'react';
import { Modal, ModalBody } from '@/components/ui/Modal';
import { validateSubdomainFormat, containsProhibitedTerm } from '@/lib/subdomain-validation-format';
import styles from './EditDNSModal.module.css';

interface Dealer {
  id: string;
  subdomain: string | null;
  domain: string;
  domainPrefix?: string;
}

interface Sibling {
  subdomain: string;
  domainPrefix: string;
  domain: string;
  businessName: string | null;
}

// The 4 available domain options
const DOMAIN_OPTIONS = [
  { value: 'myamsoil-com', label: 'myamsoil.com', domainPrefix: 'myamsoil', domain: 'com' },
  { value: 'myamsoil-ca', label: 'myamsoil.ca', domainPrefix: 'myamsoil', domain: 'ca' },
  { value: 'shopamsoil-com', label: 'shopamsoil.com', domainPrefix: 'shopamsoil', domain: 'com' },
  { value: 'shopamsoil-ca', label: 'shopamsoil.ca', domainPrefix: 'shopamsoil', domain: 'ca' },
] as const;

interface EditDNSModalProps {
  isOpen: boolean;
  onClose: () => void;
  dealer: Dealer | null;
  onSave: (
    dealerId: string,
    newSubdomain: string,
    domainPrefix: string,
    domain: string,
    bypassProhibitedTerms?: boolean
  ) => Promise<{ siblings?: Sibling[] } | void>;
}

export function EditDNSModal({ isOpen, onClose, dealer, onSave }: EditDNSModalProps) {
  const [subdomain, setSubdomain] = useState('');
  const [selectedDomain, setSelectedDomain] = useState('myamsoil-com');
  const [error, setError] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);
  const [siblings, setSiblings] = useState<Sibling[]>([]);
  const [saveSuccess, setSaveSuccess] = useState(false);

  // Detect if the current subdomain contains a prohibited term
  const prohibitedTerm = containsProhibitedTerm(subdomain);
  const hasProhibitedTerm = prohibitedTerm !== null;

  // Reset form when modal opens/closes or dealer changes
  useEffect(() => {
    if (isOpen && dealer) {
      setSubdomain(dealer.subdomain || '');
      // Set the current domain selection
      const prefix = dealer.domainPrefix || 'myamsoil';
      const dom = dealer.domain || 'com';
      setSelectedDomain(`${prefix}-${dom}`);
      setError(null);
      setIsSaving(false);
      setSiblings([]);
      setSaveSuccess(false);
    }
  }, [isOpen, dealer]);

  if (!dealer) return null;

  const currentDomainPrefix = dealer.domainPrefix || 'myamsoil';
  const currentDomain = dealer.domain || 'com';
  const currentFullDomain = `${currentDomainPrefix}.${currentDomain}`;
  const hasExistingSubdomain = !!dealer.subdomain;

  // Get the selected domain option details
  const selectedOption =
    DOMAIN_OPTIONS.find((opt) => opt.value === selectedDomain) || DOMAIN_OPTIONS[0];

  // Check if anything changed
  const subdomainChanged = subdomain !== (dealer.subdomain || '');
  const domainChanged = selectedDomain !== `${currentDomainPrefix}-${currentDomain}`;
  const hasChanges = subdomainChanged || domainChanged;

  const handleSubdomainChange = (value: string) => {
    // Auto-lowercase as user types
    const lowercased = value.toLowerCase();
    setSubdomain(lowercased);

    // Clear error on change
    if (error) setError(null);
  };

  const handleDomainChange = (value: string) => {
    setSelectedDomain(value);
    if (error) setError(null);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    // Validate subdomain
    const validation = validateSubdomainFormat(subdomain);
    if (!validation.valid) {
      // Admins can bypass prohibited term restrictions automatically
      if (hasProhibitedTerm) {
        // Continue with the save - server will handle the bypass
      } else {
        setError(validation.error || 'Invalid subdomain');
        return;
      }
    }

    setIsSaving(true);
    setError(null);

    try {
      // Automatically bypass prohibited terms for admins
      const result = await onSave(
        dealer.id,
        subdomain,
        selectedOption.domainPrefix,
        selectedOption.domain,
        hasProhibitedTerm // Auto-bypass when prohibited term detected
      );

      // Check for siblings in the response
      if (result?.siblings && result.siblings.length > 0) {
        setSiblings(result.siblings);
        setSaveSuccess(true);
        // Don't close — show the sibling warning first
      } else {
        onClose();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to update subdomain');
    } finally {
      setIsSaving(false);
    }
  };

  const footer = (
    <div className={styles.footer}>
      {saveSuccess && siblings.length > 0 && (
        <div className={styles.siblingsWarning}>
          <strong>Note:</strong> This subdomain also exists on{' '}
          {siblings.map((s, i) => (
            <span key={i}>
              {i > 0 && ', '}
              {s.subdomain}.{s.domainPrefix}.{s.domain}
              {s.businessName ? ` (${s.businessName})` : ''}
            </span>
          ))}
          . Those dealers will not be affected.
        </div>
      )}
      <div className={styles.buttons}>
        {saveSuccess ? (
          <button type="button" className={styles.confirmButton} onClick={onClose}>
            Done
          </button>
        ) : (
          <>
            <button
              type="button"
              className={styles.cancelButton}
              onClick={onClose}
              disabled={isSaving}
            >
              Cancel
            </button>
            <button
              type="submit"
              form="edit-subdomain-form"
              className={styles.confirmButton}
              disabled={isSaving || !subdomain || !hasChanges}
            >
              {isSaving ? 'Saving...' : 'Confirm'}
            </button>
          </>
        )}
      </div>
      {!saveSuccess && hasExistingSubdomain && hasChanges && (
        <div className={styles.warning}>
          <svg
            className={styles.warningIcon}
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
          >
            <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
            <line x1="12" y1="9" x2="12" y2="13" />
            <line x1="12" y1="17" x2="12.01" y2="17" />
          </svg>
          <span>
            This will break existing links to{' '}
            <strong>
              {dealer.subdomain}.{currentFullDomain}
            </strong>
          </span>
        </div>
      )}
    </div>
  );

  return (
    <Modal isOpen={isOpen} onClose={onClose} title="Edit Subdomain" size="default" footer={footer}>
      <ModalBody>
        <form id="edit-subdomain-form" onSubmit={handleSubmit} className={styles.form}>
          {hasExistingSubdomain && (
            <div className={styles.currentValue}>
              <span className={styles.label}>Current:</span>
              <code className={styles.currentSubdomain}>
                {dealer.subdomain}.{currentFullDomain}
              </code>
            </div>
          )}

          <div className={styles.inputGroup}>
            <label className={styles.label}>{hasExistingSubdomain ? 'New:' : 'Subdomain:'}</label>
            <div className={styles.combinedInput}>
              <input
                id="subdomain"
                type="text"
                value={subdomain}
                onChange={(e) => handleSubdomainChange(e.target.value)}
                placeholder="dealer-name"
                className={styles.subdomainInput}
                autoFocus
                autoComplete="off"
                disabled={isSaving}
              />
              <span className={styles.dot}>.</span>
              <select
                id="domain"
                value={selectedDomain}
                onChange={(e) => handleDomainChange(e.target.value)}
                className={styles.domainSelect}
                disabled={isSaving}
              >
                {DOMAIN_OPTIONS.map((option) => (
                  <option key={option.value} value={option.value}>
                    {option.label}
                  </option>
                ))}
              </select>
            </div>
            {error && <p className={styles.error}>{error}</p>}
          </div>

          {/* Notice when subdomain contains a normally prohibited term */}
          {hasProhibitedTerm && (
            <div className={styles.adminNotice}>
              <svg
                className={styles.noticeIcon}
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
              >
                <circle cx="12" cy="12" r="10" />
                <line x1="12" y1="8" x2="12" y2="12" />
                <line x1="12" y1="16" x2="12.01" y2="16" />
              </svg>
              <span>
                This subdomain contains &quot;{prohibitedTerm}&quot; which is normally restricted.
                Admin override will be applied.
              </span>
            </div>
          )}
        </form>
      </ModalBody>
    </Modal>
  );
}
