"use client";

import { useEffect, useState } from "react";

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

interface AddressFormProps {
  onAddressChange: (data: any) => void;
  errors: any;
}

const AddressForm = ({ onAddressChange, errors }: AddressFormProps) => {
  const [states, setStates] = useState<StateType[]>([]);
  const [loading, setLoading] = useState(true);
  const [formData, setFormData] = useState({
    first_name: '',
    last_name: '',
    email: '',
    contact_no: '',
    state_id: '',
    city: '',
    landmark: '',
    zipcode: '',
    address: ''
  });

  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 handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    const updatedData = { ...formData, [name]: value };
    setFormData(updatedData);
    onAddressChange(updatedData);
  };

  return (
    <div className="address-form">
      <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">
            <label>First Name: <span className="text-red-500">*</span></label>
            <input
              type="text"
              name="first_name"
              placeholder="First Name*"
              className={`form-control ${errors.shipping_first_name ? 'border-red-500' : ''}`}
              value={formData.first_name}
              onChange={handleChange}
              required
            />
            {errors.shipping_first_name && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_first_name}</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>Last Name: <span className="text-red-500">*</span></label>
            <input
              type="text"
              name="last_name"
              placeholder="Last Name*"
              className={`form-control ${errors.shipping_last_name ? 'border-red-500' : ''}`}
              value={formData.last_name}
              onChange={handleChange}
              required
            />
            {errors.shipping_last_name && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_last_name}</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>Email: <span className="text-red-500">*</span></label>
            <input
              type="email"
              name="email"
              placeholder="Email*"
              className={`form-control ${errors.shipping_email ? 'border-red-500' : ''}`}
              value={formData.email}
              onChange={handleChange}
              required
            />
            {errors.shipping_email && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_email}</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>Mobile Number: <span className="text-red-500">*</span></label>
            <input
              type="tel"
              name="contact_no"
              placeholder="Mobile Number*"
              className={`form-control onlyNumberKey ${errors.shipping_phone ? 'border-red-500' : ''}`}
              value={formData.contact_no}
              onChange={handleChange}
              pattern="\d{10}"
              maxLength={10}
              required
            />
            {errors.shipping_phone && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_phone}</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 select-wrapper">
            <label>State: <span className="text-red-500">*</span></label>
            <select
              id="state_id"
              className={`form-select appearance-none ${errors.shipping_state ? 'border-red-500' : ''}`}
              name="state_id"
              value={formData.state_id}
              onChange={handleChange}
              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.shipping_state && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_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.shipping_city ? 'border-red-500' : ''}`}
              value={formData.city}
              onChange={handleChange}
              required
            />
            {errors.shipping_city && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_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={handleChange}
            />
          </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.shipping_zipcode ? 'border-red-500' : ''}`}
              value={formData.zipcode}
              onChange={handleChange}
              maxLength={6}
              pattern="\d{6}"
              required
            />
            {errors.shipping_zipcode && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_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.shipping_address_line ? 'border-red-500' : ''}`}
              placeholder="Address (Area and Street)*"
              value={formData.address}
              onChange={handleChange}
              rows={3}
              required
            />
            {errors.shipping_address_line && (
              <p className="text-red-500 text-xs mt-1">{errors.shipping_address_line}</p>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddressForm;