'use client';

import { useState } from 'react';
import type { PotentialMigrationMatch } from '@/lib/migration-dealer-lookup';
import { isCustomDomain } from '@/lib/domain-utils';

interface MigrationCheckModalProps {
  match: PotentialMigrationMatch;
  onConfirm: (data: {
    subdomain: string;
    customDomain: string;
    dealerNumber: string;
    email: string;
  }) => void;
  onSkip: () => void;
  domainExtension: string;
}

type ModalStep = 'ask' | 'confirm';

/**
 * Extract subdomain from an AMSOIL domain string.
 * e.g., "jsmith.myamsoil.com" -> "jsmith"
 */
function extractSubdomain(domain: string): string {
  const match = domain.match(/^([^.]+)\.(my|shop)amsoil\.(com|ca)$/i);
  return match ? match[1] : '';
}

/**
 * Extract the apex domain name (without TLD) from a custom domain.
 * e.g., "jsmithoils.com" -> "jsmithoils"
 * e.g., "www.jsmithoils.com" -> "jsmithoils"
 * Used as a subdomain suggestion for dealers with custom domains.
 */
function extractApexName(domain: string): string {
  // Remove protocol if present
  const cleaned = domain.replace(/^https?:\/\//, '');
  // Split by dots
  const parts = cleaned.split('.');
  // Skip 'www' if present
  if (parts[0]?.toLowerCase() === 'www' && parts.length > 2) {
    return parts[1] || '';
  }
  // Return the first part (apex name)
  return parts[0] || '';
}

export default function MigrationCheckModal({
  match,
  onConfirm,
  onSkip,
  domainExtension,
}: MigrationCheckModalProps) {
  const [step, setStep] = useState<ModalStep>('ask');

  // Determine if the domain is custom or AMSOIL subdomain
  const hasCustomDomain = isCustomDomain(match.customDomain);

  // Extract subdomain from migration data:
  // - AMSOIL subdomain: extract the subdomain part (e.g., "jsmith.myamsoil.com" -> "jsmith")
  // - Custom domain: use the apex name as suggestion (e.g., "jsmithoils.com" -> "jsmithoils")
  const extractedSubdomain = match.customDomain
    ? hasCustomDomain
      ? extractApexName(match.customDomain)
      : extractSubdomain(match.customDomain)
    : '';

  // Editable form state
  const [formData, setFormData] = useState({
    email: match.contactEmail || '',
    dealerNumber: match.dealerNumber || '',
    subdomain: extractedSubdomain,
    customDomain: hasCustomDomain ? match.customDomain || '' : '',
  });

  const handleConfirm = () => {
    onConfirm(formData);
  };

  // Modal 1: Ask if coming from Empowerkit
  if (step === 'ask') {
    return (
      <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
        <div className="bg-slate-800 rounded-lg max-w-md w-full p-6 border border-slate-600">
          <h2 className="text-xl font-bold text-white mb-4">Coming from Empowerkit?</h2>
          <p className="text-white/80 mb-6">
            If you previously had a site with Empowerkit, we may be able to migrate your basic
            information and domain information automatically.
          </p>
          <div className="flex gap-3 justify-end">
            <button
              onClick={onSkip}
              className="px-4 py-2 rounded-md bg-slate-600 text-white hover:bg-slate-500 transition-colors"
            >
              No, start fresh
            </button>
            <button
              onClick={() => setStep('confirm')}
              className="px-4 py-2 rounded-md bg-sky-500 text-slate-900 font-semibold hover:bg-sky-400 transition-colors"
            >
              Yes, migrate my info
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Modal 2: Confirm/edit migration data
  return (
    <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50 p-4">
      <div className="bg-slate-800 rounded-lg max-w-lg w-full p-6 border border-slate-600">
        <h2 className="text-xl font-bold text-white mb-4">Does this information look correct?</h2>
        <p className="text-white/70 text-sm mb-4">
          You can edit any fields below before continuing.
        </p>

        <div className="space-y-4">
          {/* Contact Email */}
          <div>
            <label className="block text-sm font-medium text-white mb-1">Contact Email</label>
            <input
              type="email"
              value={formData.email}
              onChange={(e) => setFormData({ ...formData, email: e.target.value })}
              className="w-full px-3 py-2 rounded-md bg-white text-slate-900 border border-slate-300"
            />
          </div>

          {/* Dealer Number */}
          <div>
            <label className="block text-sm font-medium text-white mb-1">ZO Account Number</label>
            <input
              type="text"
              value={formData.dealerNumber}
              onChange={(e) => setFormData({ ...formData, dealerNumber: e.target.value })}
              className="w-full px-3 py-2 rounded-md bg-white text-slate-900 border border-slate-300"
            />
          </div>

          {/* Subdomain - always shown */}
          <div>
            <label className="block text-sm font-medium text-white mb-1">Subdomain</label>
            <div className="flex items-center gap-2">
              <input
                type="text"
                value={formData.subdomain}
                onChange={(e) =>
                  setFormData({ ...formData, subdomain: e.target.value.toLowerCase() })
                }
                placeholder="yourname"
                className="flex-1 px-3 py-2 rounded-md bg-white text-slate-900 border border-slate-300"
              />
              <span className="text-white/70">.myamsoil{domainExtension}</span>
            </div>
            {!hasCustomDomain && match.customDomain && (
              <p className="mt-1 text-xs text-white/50">Found: {match.customDomain}</p>
            )}
          </div>

          {/* Custom Domain - only shown if dealer has one */}
          {hasCustomDomain && (
            <div>
              <label className="block text-sm font-medium text-white mb-1">Custom Domain</label>
              <input
                type="text"
                value={formData.customDomain}
                onChange={(e) => setFormData({ ...formData, customDomain: e.target.value })}
                placeholder="yourdomain.com"
                className="w-full px-3 py-2 rounded-md bg-white text-slate-900 border border-slate-300"
              />
              <p className="mt-1 text-xs text-white/50">Found: {match.customDomain}</p>
            </div>
          )}
        </div>

        <div className="flex gap-3 justify-end mt-6">
          <button
            onClick={() => setStep('ask')}
            className="px-4 py-2 rounded-md bg-slate-600 text-white hover:bg-slate-500 transition-colors"
          >
            Back
          </button>
          <button
            onClick={handleConfirm}
            className="px-4 py-2 rounded-md bg-sky-500 text-slate-900 font-semibold hover:bg-sky-400 transition-colors"
          >
            Confirm & Continue
          </button>
        </div>
      </div>
    </div>
  );
}
