import { useState } from 'react';
import { motion } from 'framer-motion';
import { User, Mail, Phone, MessageSquare, Shield, Clock, Sparkles } from 'lucide-react';
import { Input, Button } from '@/components/ui';
import { contactPreferences } from '@/lib/pricing-data';
import type { ContactInfo, ContactPreference, QuoteResult } from '@/types/quote';
import { formatCurrency } from '@/lib/utils';

export interface Step7ContactProps {
  contactInfo: ContactInfo;
  companyNameFromStep1: string;
  quoteResult: QuoteResult | null;
  onUpdateContact: (data: Partial<ContactInfo>) => void;
  onSetContactPreference: (preference: ContactPreference) => void;
  onSetAgreedToTerms: (agreed: boolean) => void;
  onSubmit: () => void;
  isSubmitting: boolean;
}

interface FormErrors {
  name?: string;
  email?: string;
  agreedToTerms?: string;
}

export function Step7Contact({
  contactInfo,
  companyNameFromStep1,
  quoteResult,
  onUpdateContact,
  onSetContactPreference,
  onSetAgreedToTerms,
  onSubmit,
  isSubmitting,
}: Step7ContactProps) {
  const [errors, setErrors] = useState<FormErrors>({});
  const [touched, setTouched] = useState<Record<string, boolean>>({});

  if (companyNameFromStep1 && !contactInfo.companyName) {
    onUpdateContact({ companyName: companyNameFromStep1 });
  }

  const validateEmail = (email: string): boolean => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  };

  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};

    if (!contactInfo.name.trim()) {
      newErrors.name = 'Name is required';
    }

    if (!contactInfo.email.trim()) {
      newErrors.email = 'Email is required';
    } else if (!validateEmail(contactInfo.email)) {
      newErrors.email = 'Please enter a valid email address';
    }

    if (!contactInfo.agreedToTerms) {
      newErrors.agreedToTerms = 'You must agree to the terms';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleBlur = (field: string) => {
    setTouched((prev) => ({ ...prev, [field]: true }));
  };

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

    if (validateForm()) {
      onSubmit();
    } else {
      setTouched({
        name: true,
        email: true,
        agreedToTerms: true,
      });
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="max-w-2xl mx-auto"
    >
      {/* Header */}
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-[#333d49] mb-2"
            style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
          Get Your Quote
        </h2>
        <p className="text-gray-400">
          We will send your customized quote and contact you to discuss next steps.
        </p>
      </div>

      {/* Quote Preview */}
      {quoteResult && (
        <motion.div
          initial={{ opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          className="bg-gradient-navy rounded-xl p-4 sm:p-5 mb-6 sm:mb-8 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2"
        >
          <span className="text-sm sm:text-base text-white/80 font-medium">Your Estimated Monthly Total</span>
          <span className="text-xl sm:text-2xl font-bold text-white"
                style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            {formatCurrency(quoteResult.monthlyTotal)}
            <span className="text-xs sm:text-sm font-medium text-white/50 ml-1">/mo</span>
          </span>
        </motion.div>
      )}

      <form onSubmit={handleSubmit} className="space-y-5">
        {/* Contact Name */}
        <div className="space-y-2">
          <label className="flex items-center gap-2 text-sm font-medium text-[#333d49]"
                 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            <User className="w-4 h-4 text-[#fe7400]" />
            Contact Name
            <span className="text-red-500 text-xs">*</span>
          </label>
          <Input
            type="text"
            value={contactInfo.name}
            onChange={(e) => onUpdateContact({ name: e.target.value })}
            onBlur={() => handleBlur('name')}
            placeholder="Your full name"
            error={touched.name ? errors.name : undefined}
          />
        </div>

        {/* Email */}
        <div className="space-y-2">
          <label className="flex items-center gap-2 text-sm font-medium text-[#333d49]"
                 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            <Mail className="w-4 h-4 text-[#fe7400]" />
            Email Address
            <span className="text-red-500 text-xs">*</span>
          </label>
          <Input
            type="email"
            value={contactInfo.email}
            onChange={(e) => onUpdateContact({ email: e.target.value })}
            onBlur={() => handleBlur('email')}
            placeholder="you@company.com"
            error={touched.email ? errors.email : undefined}
          />
        </div>

        {/* Phone */}
        <div className="space-y-2">
          <label className="flex items-center gap-2 text-sm font-medium text-[#333d49]"
                 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            <Phone className="w-4 h-4 text-[#fe7400]" />
            Phone Number
            <span className="text-gray-300 font-normal text-xs">(recommended)</span>
          </label>
          <Input
            type="tel"
            value={contactInfo.phone}
            onChange={(e) => onUpdateContact({ phone: e.target.value })}
            placeholder="(555) 123-4567"
          />
        </div>

        {/* Current IT Situation */}
        <div className="space-y-2">
          <label className="flex items-center gap-2 text-sm font-medium text-[#333d49]"
                 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            <MessageSquare className="w-4 h-4 text-[#fe7400]" />
            Current IT Situation
            <span className="text-gray-300 font-normal text-xs">(optional)</span>
          </label>
          <textarea
            value={contactInfo.currentITSituation}
            onChange={(e) => onUpdateContact({ currentITSituation: e.target.value })}
            placeholder="Tell us about your current IT setup and any challenges you're facing..."
            rows={3}
            className="w-full px-4 py-3 rounded-xl border border-gray-200 bg-white text-[#333d49] placeholder-gray-400 hover:border-gray-300 focus:outline-none focus:ring-2 focus:ring-[#fe7400]/15 focus:border-[#fe7400] transition-all duration-200 resize-none"
          />
        </div>

        {/* Contact Preference */}
        <div className="space-y-3">
          <label className="text-sm font-medium text-[#333d49]"
                 style={{ fontFamily: "'Plus Jakarta Sans', sans-serif" }}>
            Preferred Contact Method
          </label>
          <div className="flex flex-wrap gap-4 sm:gap-5">
            {contactPreferences.map((pref) => (
              <label
                key={pref.id}
                className="flex items-center gap-2.5 cursor-pointer group"
              >
                <input
                  type="radio"
                  name="contactPreference"
                  value={pref.id}
                  checked={contactInfo.contactPreference === pref.id}
                  onChange={() => onSetContactPreference(pref.id as ContactPreference)}
                  className="w-4 h-4 text-[#fe7400] border-gray-300 focus:ring-[#fe7400]"
                />
                <span className="text-sm text-gray-500 group-hover:text-gray-700 transition-colors">
                  {pref.label}
                </span>
              </label>
            ))}
          </div>
        </div>

        {/* Terms Checkbox */}
        <div className="space-y-2 pt-4">
          <label className="flex items-start gap-3 cursor-pointer group">
            <input
              type="checkbox"
              checked={contactInfo.agreedToTerms}
              onChange={(e) => {
                onSetAgreedToTerms(e.target.checked);
                handleBlur('agreedToTerms');
              }}
              className="w-5 h-5 mt-0.5 text-[#fe7400] border-gray-300 rounded focus:ring-[#fe7400]"
            />
            <span className="text-sm text-gray-500 leading-relaxed">
              I agree to receive communications about my quote and understand that I can
              unsubscribe at any time. I have read and agree to the{' '}
              <a href="/privacy" className="text-[#fe7400] hover:text-[#e56800] font-medium transition-colors">
                Privacy Policy
              </a>{' '}
              and{' '}
              <a href="/terms" className="text-[#fe7400] hover:text-[#e56800] font-medium transition-colors">
                Terms of Service
              </a>
              .
              <span className="text-red-500 text-xs ml-0.5">*</span>
            </span>
          </label>
          {touched.agreedToTerms && errors.agreedToTerms && (
            <p className="text-sm text-red-500 ml-8">{errors.agreedToTerms}</p>
          )}
        </div>

        {/* Submit Button */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="pt-6"
        >
          <Button
            type="submit"
            variant="primary"
            size="lg"
            className="w-full text-base py-4"
            isLoading={isSubmitting}
            disabled={isSubmitting || !contactInfo.agreedToTerms}
          >
            {isSubmitting ? 'Submitting...' : (
              <>
                <Sparkles className="w-5 h-5 mr-2" />
                Submit Quote Request
              </>
            )}
          </Button>
        </motion.div>
      </form>

      {/* Trust Indicators */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.3 }}
        className="mt-10 pt-6 border-t border-gray-100"
      >
        <div className="flex flex-col sm:flex-row sm:justify-between gap-4 sm:gap-5">
          <div className="flex items-center gap-3 justify-center sm:justify-start">
            <div className="w-8 h-8 rounded-lg bg-[#ecfdf5] flex items-center justify-center flex-shrink-0">
              <Sparkles className="w-4 h-4 text-[#059669]" />
            </div>
            <span className="text-sm text-gray-500">No obligation quote</span>
          </div>
          <div className="flex items-center gap-3 justify-center">
            <div className="w-8 h-8 rounded-lg bg-[#ecfdf5] flex items-center justify-center flex-shrink-0">
              <Clock className="w-4 h-4 text-[#059669]" />
            </div>
            <span className="text-sm text-gray-500">Response within 24 hours</span>
          </div>
          <div className="flex items-center gap-3 justify-center sm:justify-end">
            <div className="w-8 h-8 rounded-lg bg-[#ecfdf5] flex items-center justify-center flex-shrink-0">
              <Shield className="w-4 h-4 text-[#059669]" />
            </div>
            <span className="text-sm text-gray-500">Your data is secure</span>
          </div>
        </div>
      </motion.div>
    </motion.div>
  );
}
