import { useNavigate } from 'react-router-dom';
import React, { useState } from 'react';
import Swal from 'sweetalert2';
import {
  FaEnvelope,
  FaUser,
  FaPhone,
  FaCalendar,
  FaComment,
  FaMapMarkerAlt
} from 'react-icons/fa';
import PhoneInput from 'react-phone-number-input';
import 'react-phone-number-input/style.css';
import { base_url } from '../../API';
import { useLoader } from '../../store/LoaderProvider';

type InquiryFormData = {
  fullName: string;
  email: string;
  phone: string;
  address: string;
  age: string;
  message: string;
};

type InquiryFormErrors = Partial<Record<keyof InquiryFormData, string>>;

const InquiryForm = () => {
  const [formData, setFormData] = useState<InquiryFormData>({
    fullName: '',
    email: '',
    phone: '',
    address: '',
    age: '',
    message: '',
  });

  const [errors, setErrors] = useState<InquiryFormErrors>({});
  const { showLoader, hideLoader } = useLoader();
  const navigate = useNavigate();

  const handleChange = (field: keyof InquiryFormData, value: string | undefined) => {
    setFormData(prev => ({ ...prev, [field]: value ?? '' }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const handleNameChange = (e) => {
    const value = e.target.value.replace(/[^a-zA-Z\s]/g, '');
    handleChange('fullName', value);
  };

  const handleAgeChange = (e) => {
    const value = e.target.value.replace(/\D/g, '');
    if (value === '' || (parseInt(value) >= 1 && parseInt(value) <= 120)) {
      handleChange('age', value);
    }
  };

  const validateForm = () => {
    const newErrors: InquiryFormErrors = {};
    let isValid = true;

    // Required fields validation
    const requiredFields: (keyof InquiryFormData)[] = ['fullName', 'email', 'phone', 'age', 'address', 'message'];

    requiredFields.forEach(field => {
      if (!formData[field]) {
        newErrors[field] = `${field.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase())} is required`;
        isValid = false;
      }
    });

    // Email validation
    if (formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
      isValid = false;
    }

    // Age validation
    if (formData.age) {
      const age = parseInt(formData.age);
      if (age < 1 || age > 120) {
        newErrors.age = 'Please enter a valid age between 1 and 120';
        isValid = false;
      }
    }

    // Phone validation
    if (formData.phone && formData.phone.length < 10) {
      newErrors.phone = 'Please enter a valid phone number';
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  };

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

    if (!validateForm()) {
      Swal.fire({
        title: 'Validation Error',
        text: 'Please fill all required fields correctly',
        icon: 'error',
        confirmButtonColor: '#e7515a'
      });
      return;
    }

    showLoader();

    try {
      const inquiryData = {
        ...formData,
        company_id: localStorage.getItem('companyId') || 1,
      };

      const response = await fetch(`${base_url}add_inquiry`, {
        method: 'POST',
        body: JSON.stringify(inquiryData),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
      });

      const data = await response.json();

      if (data.status === 'success' || data.status === true) {
        showMessage(data.message || 'Inquiry submitted successfully!', 'success');
        navigate('/inquiry');
      } else {
        throw new Error(data.message || 'Failed to submit inquiry');
      }
    } catch (err) {
      console.error('Error:', err);
      showMessage(err.message || 'An error occurred while submitting the inquiry', 'error');
    } finally {
      hideLoader();
    }
  };

  const showMessage = (message: string, status: 'success' | 'error') => {
    Swal.fire({
      title: status === 'success' ? 'Success!' : 'Error!',
      text: message,
      icon: status,
      customClass: {
        confirmButton: 'bg-[#5c4d2f] text-white px-4 py-2 rounded hover:bg-[#4a3e27]',
      },
    });
  };

  return (
    <div className="mx-auto px-4 py-8">
      <h1 className="text-3xl font-bold text-secondary dark:text-white mb-6">Submit Inquiry</h1>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Inquiry Information Section */}
        <div className="bg-white dark:bg-gray-900 rounded-lg shadow-md p-6 border border-gray-100 dark:border-gray-700">
          <h2 className="text-2xl font-semibold text-secondary dark:text-white mb-4 border-b border-primary-light pb-2">
            Inquiry Information
          </h2>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* Full Name */}
            <div className="w-full">
              <label className="block text-secondary dark:text-gray-300 font-medium mb-1">
                Full Name <span className="text-red-500">*</span>
              </label>
              <div className={`flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border ${errors.fullName ? 'border-red-500' : 'border-gray-200 dark:border-gray-700'} focus-within:border-primary focus-within:ring-1 focus-within:ring-primary-light`}>
                <FaUser className="text-primary" />
                <input
                  type="text"
                  name="fullName"
                  className="w-full bg-transparent dark:bg-gray-800 dark:text-white focus:outline-none"
                  placeholder="John Doe"
                  value={formData.fullName}
                  onChange={handleNameChange}
                  required
                  maxLength={100}
                />
              </div>
              {errors.fullName && <p className="text-red-500 text-sm mt-1">{errors.fullName}</p>}
            </div>

            {/* Email */}
            <div className="w-full">
              <label className="block text-secondary dark:text-gray-300 font-medium mb-1">
                Email <span className="text-red-500">*</span>
              </label>
              <div className={`flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border ${errors.email ? 'border-red-500' : 'border-gray-200 dark:border-gray-700'} focus-within:border-primary focus-within:ring-1 focus-within:ring-primary-light`}>
                <FaEnvelope className="text-primary" />
                <input
                  type="email"
                  name="email"
                  className="w-full bg-transparent dark:bg-gray-800 dark:text-white focus:outline-none"
                  placeholder="example@domain.com"
                  value={formData.email}
                  onChange={(e) => handleChange('email', e.target.value.trim())}
                  required
                />
              </div>
              {errors.email && <p className="text-red-500 text-sm mt-1">{errors.email}</p>}
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
            {/* Phone Number */}
            <div className="w-full">
              <label className="block text-secondary dark:text-gray-300 font-medium mb-1">
                Phone Number <span className="text-red-500">*</span>
              </label>
              <div className={`flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border ${errors.phone ? 'border-red-500' : 'border-gray-200 dark:border-gray-700'} focus-within:border-primary focus-within:ring-1 focus-within:ring-primary-light`}>
                <FaPhone className="text-primary rotate-90" />
                <PhoneInput
                  international
                  defaultCountry="US"
                  value={formData.phone}
                  onChange={(value) => handleChange('phone', value)}
                  className="w-full bg-transparent dark:bg-gray-800 dark:text-white focus:outline-none [&>input]:dark:bg-gray-800 [&>input]:dark:text-white"
                  required
                  placeholder="+1 (123) 456-7890"
                />
              </div>
              {errors.phone && <p className="text-red-500 text-sm mt-1">{errors.phone}</p>}
            </div>

            {/* Age */}
            <div className="w-full">
              <label className="block text-secondary dark:text-gray-300 font-medium mb-1">
                Age <span className="text-red-500">*</span>
              </label>
              <div className={`flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border ${errors.age ? 'border-red-500' : 'border-gray-200 dark:border-gray-700'} focus-within:border-primary focus-within:ring-1 focus-within:ring-primary-light`}>
                <FaCalendar className="text-primary" />
                <input
                  type="text"
                  name="age"
                  className="w-full bg-transparent dark:bg-gray-800 dark:text-white focus:outline-none"
                  placeholder="Enter age"
                  value={formData.age}
                  onChange={handleAgeChange}
                  required
                  maxLength={3}
                />
              </div>
              {errors.age && <p className="text-red-500 text-sm mt-1">{errors.age}</p>}
            </div>
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mt-4">
            {/* Address */}
            <div className="w-full">
              <label className="block text-secondary dark:text-gray-300 font-medium mb-1">
                Address <span className="text-red-500">*</span>
              </label>
              <div className={`flex items-center space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border ${errors.address ? 'border-red-500' : 'border-gray-200 dark:border-gray-700'} focus-within:border-primary focus-within:ring-1 focus-within:ring-primary-light`}>
                <FaMapMarkerAlt className="text-primary" />
                <input
                  type="text"
                  name="address"
                  className="w-full bg-transparent dark:bg-gray-800 dark:text-white focus:outline-none"
                  placeholder="123 Wellness Ave, Suite 200"
                  value={formData.address}
                  onChange={(e) => handleChange('address', e.target.value)}
                  required
                  maxLength={200}
                />
              </div>
              {errors.address && <p className="text-red-500 text-sm mt-1">{errors.address}</p>}
            </div>
          </div>

          <div className="grid grid-cols-1 gap-6 mt-4">
            {/* Message */}
            <div className="w-full">
              <label className="block text-secondary dark:text-gray-300 font-medium mb-1">
                Message <span className="text-red-500">*</span>
              </label>
              <div className={`flex items-start space-x-2 bg-gray-50 dark:bg-gray-800 p-2 rounded-md border ${errors.message ? 'border-red-500' : 'border-gray-200 dark:border-gray-700'} focus-within:border-primary focus-within:ring-1 focus-within:ring-primary-light`}>
                <FaComment className="text-primary mt-2" />
                <textarea
                  name="message"
                  className="w-full bg-transparent dark:bg-gray-800 dark:text-white focus:outline-none resize-none"
                  placeholder="Enter your inquiry message..."
                  value={formData.message}
                  onChange={(e) => handleChange('message', e.target.value)}
                  required
                  rows={5}
                  maxLength={1000}
                />
              </div>
              {errors.message && <p className="text-red-500 text-sm mt-1">{errors.message}</p>}
              <p className="text-gray-500 text-sm mt-1">{formData.message.length}/1000 characters</p>
            </div>
          </div>
        </div>

        {/* Form Actions */}
        <div className="flex justify-end space-x-4">
          <button
            type="button"
            onClick={() => navigate('/inquiry')}
            className="px-6 py-2 border border-gray-300 dark:border-gray-600 rounded-md text-secondary dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors"
          >
            Cancel
          </button>
          <button
            type="submit"
            className="px-6 py-2 bg-primary text-white rounded-md hover:bg-primary-light focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50 transition-colors"
          >
            Submit Inquiry
          </button>
        </div>
      </form>
    </div>
  );
};

export default InquiryForm;
