import React, { useContext, useEffect, useRef, useState } from "react";
import { ConfigContext } from "../../Context/ConfigContext";
import axios from "axios";
import { useParams } from "react-router-dom";
import { formatDateRange } from "../../Components/GlobalFunctions";

const ProjectProfileHeader = () => {
  const { projectId } = useParams();
  const { apiURL, apiHeaderJson, apiHeaderFile } = useContext(ConfigContext);
  const [profileData, setProfileData] = useState({});
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef(null);

  const GetProfileInfo = async () => {
    try {
      const response = await axios.get(`${apiURL}api/projects/${projectId}`);
      const data = response.data;

      if (data.success) {
        setProfileData(data.data);
      } else {
        setProfileData({});
      }
    } catch (error) {
      console.log(error);
    }
  };

  const GetStatus = (status) => {
    if (status === 0) {
      return "Active"
    }
    if (status === 1) {
      return "Completed"
    }
    if (status === 2) {
      return "Cancelled"
    }
  }
  const handleLogoChange = (e) => {
    const file = e.target.files[0];
    if (file) {
      // Check file type and size
      if (!file.type.startsWith('image/')) {
        alert('Please select an image file');
        return;
      }
      if (file.size > 2 * 1024 * 1024) { // 2MB limit
        alert('Image size should be less than 2MB');
        return;
      }
      handleSubmit(file);
    }
  };

  const handleSubmit = async (file) => {
    if (!file) return;

    try {
      setIsUploading(true);
      const formData = new FormData();
      formData.append("project_id", projectId);
      formData.append("project_logo", file);

      const response = await axios.post(
        `${apiURL}api/projects/UpdateProjectProfileLogo`,
        formData,
        { headers: apiHeaderFile }
      );

      if (response.data.success) {
        setProfileData(prev => ({
          ...prev,
          project_logo: response.data.project_logo
        }));
        GetProfileInfo()
      }
    } catch (error) {
      console.error("Error uploading logo:", error);
      alert('Failed to upload logo. Please try again.');
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };
  useEffect(() => {
    GetProfileInfo();
  }, []);
  return (
    <>
      <div className="profile-foreground position-relative mx-n4 mt-n4">
        <div className="profile-wid-bg">
          <img
            src="https://admin.atctransline.in/assets/images/architecture.jpg"
            alt
            className="profile-wid-img"
          />
        </div>
      </div>
      <div className="pt-4 mb-4 mb-lg-3 pb-lg-4 profile-wrapper">
        <div className="row g-4">
          <div className="col-auto">
            <div className="avatar-lg position-relative avatar-container">
              <img
                src={`https://tms.atctransline.in/apis/api/project-logo/${profileData?.project_logo}` || `https://admin.atctransline.in/assets/images/users/Noicon.jpeg`}
                alt="Project logo"
                className="img-thumbnail rounded-circle user-avatar"
                onError={(e) => {
                  e.target.src = "https://admin.atctransline.in/assets/images/users/Noicon.jpeg";
                }}
              />
              <div className="profile-edit-icon position-absolute">
                <label
                  htmlFor="profile-photo-upload"
                  className="d-flex align-items-center justify-content-center"
                  title="Change project logo"
                >
                  <i className="ri-camera-fill avatar-xs ms-3 mt-3" style={{ cursor: "pointer" }} />
                </label>
                <input
                  type="file"
                  id="profile-photo-upload"
                  accept="image/*"
                  className="d-none"
                  onChange={handleLogoChange}
                  disabled={isUploading}
                  ref={fileInputRef}
                />
              </div>
              {isUploading && (
                <div className="uploading-overlay">
                  <div className="spinner-border text-light" role="status">
                    <span className="visually-hidden">Loading...</span>
                  </div>
                </div>
              )}
            </div>
          </div>
          <div className="col">
            <div className="p-2">
              <h3 className="text-white mb-1">
                {profileData?.project_title || "-"}
              </h3>
              <p className="text-white text-opacity-75">
                {profileData?.profile_name || "-"}{" "}
              </p>
              <div className="hstack text-white-50 gap-1">
                <div className="me-2">
                  <i className="ri-map-pin-user-line me-1 text-white text-opacity-75 fs-16 align-middle" />
                  {profileData?.project_address || "-"}
                </div>
                <div>
                  <i className="ri-building-line me-1 text-white text-opacity-75 fs-16 align-middle" />
                  Project ID- {""}{profileData?.project_id}
                </div>
              </div>
            </div>
          </div>
          <div className="col">
            <div className="col-12 col-lg-auto order-last order-lg-0">
              <div className="row text text-white-50 text-center">
                <div className="col-lg-12 col-4 ">
                  <div className="d-flex justify-content-between align-items-center flex-nowrap">
                    <div className="p-2">
                      <h4 className="text-white mb-1">{profileData?.total_consultants || 0}</h4>
                      <p className="fs-14 mb-0">Consultant</p>
                    </div>
                    <div className="p-2">
                      <h4 className="text-white mb-1">{profileData?.total_contractors || 0}</h4>
                      <p className="fs-14 mb-0">Contractor</p>
                    </div>
                    <div className="p-2 text-nowrap ml-1 ">
                      <h4 className="text-white mb-1 ">
                        {formatDateRange(
                          profileData?.project_start_date,
                          profileData?.project_end_date
                        ) || 0}
                      </h4>
                      <p className="fs-14 mb-0">Duration</p>
                    </div>
                    <div className="p-2">
                      {/* <h4 className="text-white mb-1">{GetStatus(profileData?.status || "Active")}</h4> */}
                      <h4 className="text-white mb-1">{GetStatus(profileData?.project_status) || "-"}</h4>
                      <p className="fs-14 mb-0"> Status</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="col-12 col-lg-auto order-last order-lg-0">
            <div className="row text text-white-50 text-center">
              <div className="col-lg-4 col-4"></div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ProjectProfileHeader;
