"use client";

import React, { useState, useEffect } from "react";
import { Outlet } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "../../../store";
import {
  allAddress,
  deleteAddress,
  updateProfileBuyer,
  profileBuyer,
} from "../../../api/api";
import { toast } from "react-toastify";
import AddressCard from "../../../components/bayerProfile/pages/components/AddressCard";
import AddressForm from "../../../components/bayerProfile/pages/components/AddressForm";
import Swal from "sweetalert2";

const ProfilePage = () => {
  const dispatch = useDispatch<any>();
  const { data } = useSelector((state: RootState) => state.AddressReducer);
  const { buyerProfile } = useSelector(
    (state: RootState) => state.profileReducer
  );
  console.log();
  const addresses = data?.data?.addresses || [];

  const [formData, setFormData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    companyName: "",
    phone: "",
  });

  const [errors, setErrors] = useState({
    firstName: "",
    lastName: "",
    email: "",
    phone: "",
  });

  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [showForm, setShowForm] = useState(false);
  const [editingAddress, setEditingAddress] = useState<any>(null);
  useEffect(() => {
    if (showForm) {
      document.body.classList.add("overflow-hidden");
    } else {
      document.body.classList.remove("overflow-hidden");
    }

    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, [showForm]);

  // Set form data when buyerProfile data is available
  useEffect(() => {
    if (buyerProfile?.data) {
      setFormData({
        firstName: buyerProfile?.data?.first_name || "",
        lastName: buyerProfile?.data?.last_name || "",
        email: buyerProfile?.data?.email || "",
        companyName: buyerProfile?.data?.company_name || "",
        phone: buyerProfile?.data?.phone || "",
      });
    }
  }, [buyerProfile]);

  useEffect(() => {
    dispatch(allAddress());
  }, [dispatch]);

  const validateForm = () => {
    let isValid = true;
    const newErrors = {
      firstName: "",
      lastName: "",
      email: "",
      phone: "",
    };

    if (!formData.firstName.trim()) {
      newErrors.firstName = "First name is required";
      isValid = false;
    } else if (formData.firstName.length < 2) {
      newErrors.firstName = "First name must be at least 2 characters";
      isValid = false;
    }

    if (!formData.lastName.trim()) {
      newErrors.lastName = "Last name is required";
      isValid = false;
    } else if (formData.lastName.length < 2) {
      newErrors.lastName = "Last name must be at least 2 characters";
      isValid = false;
    }

    if (!formData.email.trim()) {
      newErrors.email = "Email is required";
      isValid = false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = "Please enter a valid email address";
      isValid = false;
    }

    if (!formData.phone.trim()) {
      newErrors.phone = "Phone number is required";
      isValid = false;
    } else if (!/^\d+$/.test(formData.phone)) {
      newErrors.phone = "Phone number must contain only digits";
      isValid = false;
    } else if (formData.phone.length < 10) {
      newErrors.phone = "Phone number must be at least 10 digits";
      isValid = false;
    } else if (formData.phone.length > 15) {
      newErrors.phone = "Phone number cannot exceed 15 digits";
      isValid = false;
    }

    setErrors(newErrors);
    return isValid;
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });

    // Clear error when user starts typing
    if (errors[name as keyof typeof errors]) {
      setErrors({ ...errors, [name]: "" });
    }
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0];

      // Validate file type and size
      const validTypes = ["image/jpeg", "image/png", "image/gif"];
      const maxSize = 2 * 1024 * 1024; // 2MB

      if (!validTypes.includes(file.type)) {
        toast.error("Please upload a valid image file (JPEG, PNG, GIF)");
        return;
      }

      if (file.size > maxSize) {
        toast.error("Image size should be less than 2MB");
        return;
      }

      setSelectedFile(file);
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      toast.error("Please fix the errors in the form");
      return;
    }

    const updatedProfile = new FormData();

    if (selectedFile) {
      updatedProfile.append("profile", selectedFile);
    }
    updatedProfile.append("first_name", formData.firstName);
    updatedProfile.append("last_name", formData.lastName);
    updatedProfile.append("email", formData.email);
    updatedProfile.append("phone", formData.phone);
    updatedProfile.append("company_name", formData.companyName);

    try {
      const response: any = await dispatch(updateProfileBuyer(updatedProfile));
      if (response?.payload?.status_code === 200) {
        toast.success("Profile updated successfully!");
        await dispatch(profileBuyer());
        await dispatch(allAddress());
      } else {
        toast.error(response?.payload?.error || "Failed to update profile.");
      }
    } catch {
      toast.error("An error occurred. Please try again.");
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await dispatch(deleteAddress({ id })).unwrap();
      toast.success("Address deleted successfully!");
      await dispatch(allAddress());
    } catch (error: any) {
      Swal.fire({
        icon: "error",
        text: error?.message || "Failed to delete address!",
      });
    }
  };

  return (
    <div>
      {/* {/ Profile Section /} */}
      <div className="max-w-5xl bg-white shadow-lg rounded-lg p-6 border border-gray-200">
        <div className="flex justify-between items-center border-b border-gray-300 pb-3">
          <h2 className="text-2xl font-semibold">Edit Profile</h2>
          <button onClick={handleSubmit} className="animation-custom-button">
            Save Changes
          </button>
        </div>

        <p className="text-sm text-gray-500 mb-4 text-center">
          Only your name and profile photo will be displayed on your public
          profile.
        </p>

        {/* {/ Profile Picture Upload /} */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 ">
          <div>
            <label className="block text-base text-black font-medium text-start">
              Profile Photo
            </label>
            <input
              type="file"
              onChange={handleFileChange}
              accept="image/jpeg, image/png, image/gif"
              className="mt-1 border border-gray-300 pt-[5px] px-2  h-[42px] rounded w-full"
            />
            <p className="text-xs text-gray-500 mt-1 text-center">
              JPEG, PNG or GIF (Max 2MB)
            </p>
          </div>

          {/* {/ Phone Number Field /} */}
          <div>
            <label className="block text-base text-black font-medium text-start">
              Phone
            </label>
            <input
              type="tel"
              name="phone"
              value={formData.phone}
              onChange={handleChange}
              className={`w-full p-2 border ${
                errors.phone ? "border-red-500" : "border-gray-300"
              } rounded mt-1`}
              placeholder="Enter phone number"
            />
            {errors.phone && (
              <p className="text-red-500 text-xs mt-1">{errors.phone}</p>
            )}
          </div>
        </div>

        {/* {/ Profile Form /} */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
          {[
            { label: "First Name", name: "firstName", required: true },
            { label: "Last Name", name: "lastName", required: true },
            {
              label: "Email Address",
              name: "email",
              disabled: true,
              required: true,
            },
            { label: "Company Name", name: "companyName", required: false },
          ].map(({ label, name, disabled, required }) => (
            <div key={name}>
              <label className="block text-base text-black font-medium text-start">
                {label} {required && <span className="text-red-500">*</span>}
              </label>
              <input
                type={name === "email" ? "email" : "text"}
                name={name}
                value={formData[name as keyof typeof formData]}
                onChange={handleChange}
                disabled={disabled}
                className={`w-full p-2 border ${
                  disabled
                    ? "bg-gray-100"
                    : errors[name as keyof typeof errors]
                    ? "border-red-500"
                    : "border-gray-300"
                } rounded mt-1`}
              />
              {errors[name as keyof typeof errors] && (
                <p className="text-red-500 text-xs mt-1">
                  {errors[name as keyof typeof errors]}
                </p>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* {/ Address Section /} */}
      <div className="bg-white shadow-lg rounded-lg  mt-4 mb-4">
        <div className="p-6 ">
          <div className="flex justify-between items-center border-b border-gray-200 pb-3">
            <h2 className="text-2xl font-semibold">Address</h2>
            <button
              type="button"
              className="animation-custom-button"
              onClick={() => {
                setShowForm(true);
                setEditingAddress(null);
              }}
            >
              Add Address
            </button>
          </div>

          <div className="lg:flex xs:flex-none gap-8 capitalize mt-4 overflow-auto">
            {addresses.map((address: any, index: number) => (
              <AddressCard
                key={address.id}
                fullname={address.fullname}
                address={`${address.house_number}`}
                city={address?.city}
                state={address?.state}
                postal_code={address?.postal_code}
                country={address.country}
                location={address.location}
                province={address.province}
                // phone_number={address.phone_number}
                house_number={address.house_number}
                onEdit={() => {
                  setEditingAddress(address);
                  setShowForm(true);
                }}
                onDelete={() => handleDelete(address.id)}
                isLast={index === addresses.length - 1}
              />
            ))}
          </div>

          {/* {/ Address Modal /} */}
          {showForm && (
            <div className="fixed top-0 left-0 w-full h-full  bg-black bg-opacity-50 flex justify-center items-center z-50 overflow-scroll pt-[250px] md:pt-0 pb-[20px] md:pb-0">
              <div>
                <AddressForm
                  onClose={() => setShowForm(false)}
                  initialValues={editingAddress || {}}
                />
              </div>
            </div>
          )}
        </div>
      </div>

      <div className="bg-gray-100 right_section">
        <Outlet />
      </div>
    </div>
  );
};

export default ProfilePage;
