import React, { useState } from 'react';

import { useAppStateContext } from '../context/user.data.context';
import { verifyUser, getUser } from '../service/user/user.service';
import { recomaze_ai_personalization_env } from '../env';
import type { IUser } from '../types';

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const PHONE_REGEX = /^\+[1-9]\d{7,14}$/;

const VerificationModal = (): JSX.Element | null => {
  const { user, setUser } = useAppStateContext();

  const [email, setEmail] = useState(user?.email || '');
  const [phoneNumber, setPhoneNumber] = useState('');
  const [emailError, setEmailError] = useState('');
  const [phoneError, setPhoneError] = useState('');
  const [apiError, setApiError] = useState('');
  const [submitting, setSubmitting] = useState(false);

  if (!user || user.verified) return null;

  const validate = (): boolean => {
    let valid = true;

    if (!email.trim() || !EMAIL_REGEX.test(email.trim())) {
      setEmailError('Please enter a valid email address.');
      valid = false;
    } else {
      setEmailError('');
    }

    if (!phoneNumber.trim() || !PHONE_REGEX.test(phoneNumber.trim())) {
      setPhoneError(
        'Please enter a valid phone number in international format (e.g. +12025551234).'
      );
      valid = false;
    } else {
      setPhoneError('');
    }

    return valid;
  };

  const handleSubmit = async () => {
    if (!validate()) return;

    setSubmitting(true);
    setApiError('');

    try {
      const response = await verifyUser({
        email: email.trim(),
        phone_number: phoneNumber.trim(),
      });

      if (response?.success || response?.verified) {
        const userResponse = await getUser();
        if (userResponse?.success) {
          setUser(userResponse);
        } else {
          setUser({ ...user, verified: true } as IUser);
        }
      } else {
        setApiError(
          response?.message ||
            response?.error ||
            'Verification failed. Please try again.'
        );
      }
    } catch {
      setApiError('Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[99999] flex items-center justify-center bg-black/50 p-4">
      <div className="relative w-full max-w-[480px] bg-white rounded-xl shadow-2xl overflow-hidden">
        {/* Header with logo */}
        <div className="flex flex-col items-center pt-8 pb-2 px-6">
          <img
            src={recomaze_ai_personalization_env?.plugin_icon}
            alt="Recomaze"
            className="w-10 h-10 object-contain mb-4"
          />
          <h2 className="text-xl font-semibold text-gray-900 text-center">
            Where should we send your weekly AI performance reports?
          </h2>
          <p className="text-sm text-gray-500 text-center mt-2 leading-relaxed max-w-[380px]">
            Every week we{`'`}ll show you which AI engines recommend you vs
            competitors, what customers ask AI about your products, and critical
            catalog issues. Use an inbox you check regularly.
          </p>
        </div>

        {/* Form */}
        <div className="px-6 pt-4 pb-6 space-y-4">
          {/* Email */}
          <div>
            <label
              htmlFor="verification-email"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Email
            </label>
            <input
              id="verification-email"
              type="email"
              value={email}
              onChange={e => {
                setEmail(e.target.value);
                if (emailError) setEmailError('');
              }}
              placeholder="you@company.com"
              className={`w-full px-3 py-2 border rounded-lg text-sm outline-none transition-colors ${
                emailError
                  ? 'border-red-400 focus:border-red-500'
                  : 'border-gray-300 focus:border-[#7929A6]'
              }`}
            />
            {emailError && (
              <p className="text-xs text-red-500 mt-1">{emailError}</p>
            )}
          </div>

          {/* Phone */}
          <div>
            <label
              htmlFor="verification-phone"
              className="block text-sm font-medium text-gray-700 mb-1"
            >
              Phone number
            </label>
            <input
              id="verification-phone"
              type="tel"
              value={phoneNumber}
              onChange={e => {
                setPhoneNumber(e.target.value);
                if (phoneError) setPhoneError('');
              }}
              placeholder="+12025551234"
              className={`w-full px-3 py-2 border rounded-lg text-sm outline-none transition-colors ${
                phoneError
                  ? 'border-red-400 focus:border-red-500'
                  : 'border-gray-300 focus:border-[#7929A6]'
              }`}
            />
            {phoneError && (
              <p className="text-xs text-red-500 mt-1">{phoneError}</p>
            )}
          </div>

          {/* API error */}
          {apiError && (
            <div className="bg-red-50 border border-red-200 rounded-lg px-3 py-2">
              <p className="text-xs text-red-600">{apiError}</p>
            </div>
          )}

          {/* Submit button */}
          <button
            onClick={handleSubmit}
            disabled={submitting}
            className="w-full text-white bg-gradient-to-r from-[#7929A6] to-[#E84774] px-5 py-2.5 rounded-lg text-sm font-semibold transition-opacity hover:opacity-90 disabled:opacity-60 disabled:cursor-not-allowed"
          >
            {submitting ? 'Saving...' : 'Save and continue'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default VerificationModal;
