import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import axiosInstance from "../../../utils/axiosConfig";
import {
  USERS_URL,
  COUNTRY_URL,
  LOCATIONS_URL,
  ROLES_URL,
  ACCOUNT_STATUS_URL,
} from "../../../utils/config";
import SuccessPopup from "../../common/SuccessPopup";
import UserProfileForm from "./pages/UserProfileForm";
import "./styles/UserProfile.css";

const UserProfile = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    employee_id: "",
    employee_name: "",
    email_id: "",
    phonenumber: "",
    department_id: "",
    country_id: "",
    location_id: "",
    status_id: "",
    role_ids: [],
  });
  const [departments, setDepartments] = useState([]);
  const [countries, setCountries] = useState([]);
  const [locations, setLocations] = useState([]);
  const [roles, setRoles] = useState([]);
  const [accountStatuses, setAccountStatuses] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loadingData, setLoadingData] = useState(true);
  const [error, setError] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoadingData(true);
        setError(null);

        const [countryRes, rolesRes, statusRes, userRes] =
          await Promise.all([
            axiosInstance.get(COUNTRY_URL),
            axiosInstance.get(ROLES_URL),
            axiosInstance.get(ACCOUNT_STATUS_URL),
            axiosInstance.get(`${USERS_URL}/${id}`),
          ]);

        if (countryRes.data.success) setCountries(countryRes.data.data || []);
        if (rolesRes.data.success) setRoles(rolesRes.data.data || []);
        if (statusRes.data.success)
          setAccountStatuses(statusRes.data.data || []);

        if (userRes.data.success) {
          const user = userRes.data.data;

          let countryId = "";
          if (user.location_id) {
            try {
              const locationRes = await axiosInstance.get(
                `${LOCATIONS_URL}/${user.location_id}`
              );
              if (locationRes.data.success && locationRes.data.data) {
                countryId = locationRes.data.data.country_id || "";
              }
            } catch (err) {
              console.error("Error fetching location:", err);
            }
          }

          setFormData({
            employee_id: user.employee_id || "",
            employee_name: user.employee_name || "",
            email_id: user.email_id || "",
            phonenumber: user.phonenumber || "",
            department_id: user.department_id || "",
            country_id: countryId,
            location_id: user.location_id || "",
            status_id: user.status_id || "",
            role_ids: user.roles ? user.roles.map((r) => r.role_id) : [],
          });

          if (countryId) {
            try {
              const locationsRes = await axiosInstance.get(
                `${LOCATIONS_URL}/country/${countryId}`
              );
              if (locationsRes.data.success) {
                setLocations(locationsRes.data.data || []);
              }
            } catch (err) {
              console.error("Error fetching locations:", err);
            }
          }
          if (user.location_id) {
            try {
              const deptRes = await axiosInstance.get(
                `${LOCATIONS_URL}/${user.location_id}/departments`
              );
              if (deptRes.data.success) {
                setDepartments(deptRes.data.data || []);
              }
            } catch (err) {
              console.error("Error fetching departments for location:", err);
            }
          }
        } else {
          setError("User not found");
        }
      } catch (err) {
        console.error("Error fetching data:", err);
        setError(err.response?.data?.message || "Failed to load user data");
      } finally {
        setLoadingData(false);
      }
    };

    if (id) {
      fetchData();
    }
  }, [id]);

  useEffect(() => {
    const fetchLocationsByCountry = async () => {
      if (!formData.country_id) {
        setLocations([]);
        setDepartments([]);
        if (formData.location_id) {
          setFormData((prev) => ({ ...prev, location_id: "", department_id: "" }));
        }
        return;
      }

      try {
        const response = await axiosInstance.get(
          `${LOCATIONS_URL}/country/${formData.country_id}`
        );
        if (response.data.success) {
          setLocations(response.data.data || []);
          const locationIds = response.data.data.map((loc) => loc.location_id);
          if (
            formData.location_id &&
            !locationIds.includes(parseInt(formData.location_id))
          ) {
            setFormData((prev) => ({ ...prev, location_id: "", department_id: "" }));
          }
        }
      } catch (err) {
        console.error("Error fetching locations by country:", err);
        setLocations([]);
      }
    };

    fetchLocationsByCountry();
  }, [formData.country_id]);

  useEffect(() => {
    const fetchDepartmentsByLocation = async () => {
      if (!formData.location_id) {
        setDepartments([]);
        return;
      }

      try {
        const response = await axiosInstance.get(
          `${LOCATIONS_URL}/${formData.location_id}/departments`
        );
        if (response.data.success) {
          setDepartments(response.data.data || []);
          const deptIds = (response.data.data || []).map((d) => d.department_id);
          if (
            formData.department_id &&
            !deptIds.includes(parseInt(formData.department_id))
          ) {
            setFormData((prev) => ({ ...prev, department_id: "" }));
          }
        }
      } catch (err) {
        console.error("Error fetching departments by location:", err);
        setDepartments([]);
      }
    };

    fetchDepartmentsByLocation();
  }, [formData.location_id]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => {
      if (name === "country_id") {
        return { ...prev, [name]: value, location_id: "", department_id: "" };
      }
      if (name === "location_id") {
        return { ...prev, [name]: value, department_id: "" };
      }
      return { ...prev, [name]: value };
    });
  };

  const handleRoleChange = (roleId) => {
    setFormData((prev) => ({
      ...prev,
      role_ids: roleId !== "" && roleId != null ? [Number(roleId)] : [],
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError(null);

    if (
      !formData.employee_name ||
      !formData.email_id ||
      formData.role_ids.length === 0
    ) {
      setError("Please fill in all required fields");
      setLoading(false);
      return;
    }

    try {
      const response = await axiosInstance.put(`${USERS_URL}/${id}`, {
        status_id: formData.status_id
          ? parseInt(formData.status_id)
          : undefined,
        employee_name: formData.employee_name,
        email_id: formData.email_id,
        phonenumber: formData.phonenumber || null,
        department_id: formData.department_id
          ? parseInt(formData.department_id)
          : null,
        location_id: formData.location_id
          ? parseInt(formData.location_id)
          : null,
        role_ids: formData.role_ids,
      });

      if (response.data.success) {
        setPopupMessage("User updated successfully!");
        setShowPopup(true);
      }
    } catch (err) {
      setError(err.response?.data?.message || "Failed to update user");
      console.error("Error updating user:", err);
    } finally {
      setLoading(false);
    }
  };

  if (loadingData) {
    return (
      <div className="form-section user-profile-loading">
        <p>Loading user data...</p>
      </div>
    );
  }

  return (
    <>
      <SuccessPopup
        show={showPopup}
        message={popupMessage}
        onClose={() => setShowPopup(false)}
        onOk={() => {
          setShowPopup(false);
          navigate("/user-create");
        }}
      />

      <UserProfileForm
        formData={formData}
        departments={departments}
        countries={countries}
        locations={locations}
        roles={roles}
        accountStatuses={accountStatuses}
        loading={loading}
        error={error}
        onInputChange={handleChange}
        onRoleChange={handleRoleChange}
        onSubmit={handleSubmit}
      />
    </>
  );
};

export default UserProfile;
