import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import axiosInstance from "../../../utils/axiosConfig";
import {
  USERS_URL,
  COUNTRY_URL,
  LOCATIONS_URL,
  ROLES_URL,
} from "../../../utils/config";
import SuccessPopup from "../../common/SuccessPopup";
import ErrorPopup from "../../common/ErrorPopup";
import { useScrollToError } from "../../../hooks/useScrollToError";
import UserCreateForm from "./pages/UserCreateForm";
import "../form/styles/CreateForm.css";
import "./styles/UserCreate.css";
import "./styles/UserCreateForm.css";
import "./styles/UsersList.css";

const MAX_USER_IMAGE_SIZE_MB = 10;
const MAX_USER_IMAGE_SIZE_BYTES = MAX_USER_IMAGE_SIZE_MB * 1024 * 1024;

const UserCreate = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    employee_id: "",
    employee_name: "",
    email_id: "",
    phonenumber: "",
    department_id: "",
    country_id: "",
    location_id: "",
    password: "",
    role_ids: [],
    user_image: null,
    user_image_preview: null,
  });
  const imageInputRef = React.useRef(null);
  const [departments, setDepartments] = useState([]);
  const [countries, setCountries] = useState([]);
  const [locations, setLocations] = useState([]);
  const [roles, setRoles] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  useScrollToError(error);
  const [loadingRoles, setLoadingRoles] = useState(true);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoadingRoles(true);
        const [countryRes, rolesRes] = await Promise.all([
          axiosInstance.get(COUNTRY_URL),
          axiosInstance.get(ROLES_URL),
        ]);

        if (countryRes.data.success) setCountries(countryRes.data.data || []);

        if (rolesRes.data.success) {
          const rolesData = rolesRes.data.data || [];
          setRoles(rolesData);
        } else {
          console.error("Roles API response not successful:", rolesRes.data);
        }
      } catch (err) {
        console.error("Error fetching data:", err);
        setError("Failed to load form data");
      } finally {
        setLoadingRoles(false);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    const fetchLocationsByCountry = async () => {
      if (!formData.country_id) {
        setLocations([]);
        return;
      }

      try {
        const response = await axiosInstance.get(
          `${LOCATIONS_URL}/country/${formData.country_id}`
        );
        if (response.data.success) {
          setLocations(response.data.data || []);
        }
      } 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 || []);
        }
      } 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 handleImageChange = (e) => {
    const file = e.target.files?.[0];
    if (!file) {
      setFormData((prev) => ({ ...prev, user_image: null, user_image_preview: null }));
      return;
    }
    if (!file.type.startsWith("image/")) {
      setError("Please select an image file (JPEG, PNG, GIF, or WebP).");
      return;
    }
    if (file.size > MAX_USER_IMAGE_SIZE_BYTES) {
      setError(`Image must be ${MAX_USER_IMAGE_SIZE_MB} MB or smaller.`);
      return;
    }
    setError(null);
    const reader = new FileReader();
    reader.onloadend = () => {
      setFormData((prev) => ({
        ...prev,
        user_image: file,
        user_image_preview: reader.result,
      }));
    };
    reader.readAsDataURL(file);
  };

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

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

    const getBase64 = (file) =>
      new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });

    try {
      let photo_base64 = null;
      if (formData.user_image) {
        photo_base64 = await getBase64(formData.user_image);
      }
      const payload = {
        employee_id: formData.employee_id,
        status_id: 1,
        employee_name: formData.employee_name,
        email_id: formData.email_id,
        phonenumber: formData.phonenumber,
        department_id: parseInt(formData.department_id),
        location_id: parseInt(formData.location_id),
        password: formData.password,
        role_ids: formData.role_ids,
      };
      if (photo_base64 != null) {
        payload.photo_base64 = photo_base64;
      }
      const response = await axiosInstance.post(USERS_URL, payload);

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

  const clearForm = () => {
    setFormData({
      employee_id: "",
      employee_name: "",
      email_id: "",
      phonenumber: "",
      department_id: "",
      country_id: "",
      location_id: "",
      password: "",
      role_ids: [],
      user_image: null,
      user_image_preview: null,
    });
    setError(null);
    if (imageInputRef.current) imageInputRef.current.value = "";
  };

  return (
    <>
      <SuccessPopup
        show={showPopup}
        message={popupMessage}
        onClose={() => setShowPopup(false)}
      />
      <ErrorPopup
        show={!!error}
        message={error || ""}
        onClose={() => setError(null)}
      />

      <div className="create-form-container">
        <div className="create-form-header">
          <h1 className="create-form-title">Create User</h1>
          <button
            type="button"
            className="btn btn-secondary"
            onClick={() => navigate("/users")}
          >
            Cancel
          </button>
        </div>

        {error && (
          <div className="error-message">{error}</div>
        )}

        <UserCreateForm
          formData={formData}
          departments={departments}
          countries={countries}
          locations={locations}
          roles={roles}
          loading={loading}
          loadingRoles={loadingRoles}
          onInputChange={handleChange}
          onRoleChange={handleRoleChange}
          onImageChange={handleImageChange}
          imageInputRef={imageInputRef}
          onSubmit={handleSubmit}
          onClearForm={clearForm}
        />
      </div>
    </>
  );
};

export default UserCreate;
