"use client";

import React, { useState, useEffect } from 'react';

interface StateType {
  _id: string;
  name: string;
}

interface BillingAddressProps {
  onAddressChange: (data: any, sameAsShipping: boolean) => void;
  errors: any;
}

const BillingAddress = ({ onAddressChange, errors }: BillingAddressProps) => {
  const [sameAsShipping, setSameAsShipping] = useState(true);
  const [states, setStates] = useState<StateType[]>([]);
  const [loading, setLoading] = useState(true);
  const [formData, setFormData] = useState({
    full_name: '',
    mobile: '',
    email: '',
    state: '',
    city: '',
    landmark: '',
    zipcode: '',
    address: '',
    same_as_shipping: true
  });

  useEffect(() => {
    const fetchStates = async () => {
      try {
        const response = await fetch("/api/states");
        if (!response.ok) throw new Error("Failed to fetch states");
        const data = await response.json();
        setStates(data.data || data);
      } catch (error) {
        console.error("Error fetching states:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchStates();
  }, []);

  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const checked = e.target.checked;
    setSameAsShipping(checked);
    setFormData(prev => ({ ...prev, same_as_shipping: checked }));
    onAddressChange(checked ? null : formData, checked);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    const updatedData = { ...formData, [name]: value, same_as_shipping: false };
    setFormData(updatedData);
    setSameAsShipping(false);
    onAddressChange(updatedData, false);
  };

  return (
    <div className="card card-grey mb-3 sm:mb-0 mt-2">
      <div className="card-body">
        <h3>BILLING ADDRESS</h3>
        
        <div className="customCheckbox clearfix py-2 my-2">
          <input 
            id="same_as_shipping" 
            name="same_ship_addr" 
            type="checkbox" 
            value="1"
            checked={sameAsShipping}
            onChange={handleCheckboxChange}
          /> 
          <label htmlFor="same_as_shipping">The same as shipping address</label>
        </div>

        {!sameAsShipping && (
          <div className="billing-address-form mt-4">
            <div className="flex flex-wrap -mx-2 lg:-mx-3 mt-2">
              <div className="2xl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-6/12 sm:w-full w-full px-2 lg:px-3 mb-2 sm:mb-3">
                <div className="form-group select-wrapper">
                  <label>State: <span className="text-red-500">*</span></label>
                  <select
                    id="billing_state"
                    className={`form-select appearance-none ${errors.billing_state ? 'border-red-500' : ''}`}
                    name="state"
                    value={formData.state}
                    onChange={handleInputChange}
                    required
                  >
                    <option value="">
                      {loading ? "Loading States..." : "Select a State"}
                    </option>
                    {states.map((state) => (
                      <option key={state._id} value={state._id}>
                        {state.name}
                      </option>
                    ))}
                  </select>
                  {errors.billing_state && (
                    <p className="text-red-500 text-xs mt-1">{errors.billing_state}</p>
                  )}
                </div>
              </div>

              <div className="2xl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-6/12 sm:w-full w-full px-2 lg:px-3 mb-2 sm:mb-3">
                <div className="form-group">
                  <label>City: <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    name="city"
                    placeholder="City*"
                    className={`form-control ${errors.billing_city ? 'border-red-500' : ''}`}
                    value={formData.city}
                    onChange={handleInputChange}
                    required
                  />
                  {errors.billing_city && (
                    <p className="text-red-500 text-xs mt-1">{errors.billing_city}</p>
                  )}
                </div>
              </div>

              <div className="2xl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-6/12 sm:w-full w-full px-2 lg:px-3 mb-2 sm:mb-3">
                <div className="form-group">
                  <label>Landmark:</label>
                  <input
                    type="text"
                    name="landmark"
                    placeholder="Landmark"
                    className="form-control"
                    value={formData.landmark}
                    onChange={handleInputChange}
                  />
                </div>
              </div>

              <div className="2xl:w-6/12 xl:w-6/12 lg:w-6/12 md:w-6/12 sm:w-full w-full px-2 lg:px-3 mb-2 sm:mb-3">
                <div className="form-group">
                  <label>Zip/Postal Code: <span className="text-red-500">*</span></label>
                  <input
                    type="text"
                    name="zipcode"
                    placeholder="Zip/Postal Code*"
                    className={`form-control ${errors.billing_zipcode ? 'border-red-500' : ''}`}
                    value={formData.zipcode}
                    onChange={handleInputChange}
                    maxLength={6}
                    pattern="\d{6}"
                    required
                  />
                  {errors.billing_zipcode && (
                    <p className="text-red-500 text-xs mt-1">{errors.billing_zipcode}</p>
                  )}
                </div>
              </div>

              <div className="w-full px-2 lg:px-3 mb-2 sm:mb-3">
                <div className="form-group">
                  <label>Address: <span className="text-red-500">*</span></label>
                  <textarea
                    name="address"
                    className={`form-control ${errors.billing_address_line ? 'border-red-500' : ''}`}
                    placeholder="Address (Area and Street)*"
                    rows={3}
                    value={formData.address}
                    onChange={handleInputChange}
                    required
                  />
                  {errors.billing_address_line && (
                    <p className="text-red-500 text-xs mt-1">{errors.billing_address_line}</p>
                  )}
                </div>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default BillingAddress;