import React, { useContext, useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { ConfigContext } from "../../Context/ConfigContext";
import axios from "axios";
import ReactECharts from 'echarts-for-react';

const Dashboard = () => {
  const { apiURL, apiHeaderJson, imageURL, user_profile_id } = useContext(ConfigContext);

  const [loading, setLoading] = useState(false);
  const [clientInfo, setClientInfo] = useState(null);
  const [project, setProject] = useState(null);
  const [projectItems, setProjectItems] = useState([]);
  const [projectRequests, setProjectRequests] = useState([]);
  const [projectTasks, setProjectTasks] = useState([]);
  const [projectGallery, setProjectGallery] = useState([]);
  const [expandedTaskId, setExpandedTaskId] = useState(null);

  const getDashboardData = async () => {
    try {
      setLoading(true);
      const headers = apiHeaderJson;
      const response = await axios.get(`${apiURL}api/GetDashboardForClient`, {
        headers,
        params: { client_id: user_profile_id }
      });
      const { success, data } = response.data;

      if (success) {
        setClientInfo(data?.client_info);
        const allProjects = data?.tabs?.total_projects || [];
        const currentProject = allProjects.length > 0 ? allProjects[0] : null;
        setProject(currentProject);
        setProjectItems(currentProject?.project_items || []);
        setProjectRequests(data?.tabs?.projects_requests || []);
        setProjectTasks(currentProject?.project_tasks || []);
        setProjectGallery(currentProject?.project_gallary || []);
      } else {
        setClientInfo(null);
        setProject(null);
        setProjectItems([]);
        setProjectRequests([]);
        setProjectTasks([]);
        setProjectGallery([]);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    getDashboardData();
  }, [user_profile_id]);

  const getStatusColor = (status) => {
    switch (Number(status)) {
      case 0: return "warning";
      case 1: return "info";
      case 2: return "success";
      case 3: return "danger";
      case 4: return "secondary";
      default: return "primary";
    }
  };

  const getProjectStatusLabel = (status) => {
    switch (Number(status)) {
      case 0: return "Active";
      case 1: return "In-Active";
      case 2: return "Completed";
      default: return "Unknown";
    }
  };

  const getTaskPriorityLabel = (priority) => {
    switch (Number(priority)) {
      case 1: return { label: "Low", color: "success" };
      case 2: return { label: "Medium", color: "warning" };
      case 3: return { label: "High", color: "danger" };
      default: return { label: "Normal", color: "secondary" };
    }
  };

  const getTaskStatusLabel = (status) => {
    switch (Number(status)) {
      case 0: return { label: "Pending", color: "warning" };
      case 1: return { label: "In Progress", color: "info" };
      case 2: return { label: "Completed", color: "success" };
      default: return { label: "Unknown", color: "secondary" };
    }
  };

  const getItemChartOption = () => {
    const itemNames = projectItems.map(item => item.item_name || 'Unknown');
    const qtyData = projectItems.map(item => item.pi_item_qty || 0);
    const receivedData = projectItems.map(item => item.pi_item_received_qty || 0);
    const remainingData = projectItems.map(item => (item.pi_item_qty || 0) - (item.pi_item_received_qty || 0));

    return {
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: ['Total Quantity', 'Received', 'Remaining'], bottom: 0, textStyle: { fontSize: 11 } },
      grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
      xAxis: { type: 'category', data: itemNames, axisLabel: { rotate: 30, fontSize: 10 } },
      yAxis: { type: 'value', name: 'Quantity' },
      series: [
        { name: 'Total Quantity', type: 'bar', data: qtyData, itemStyle: { color: '#405189' }, barGap: '10%' },
        { name: 'Received', type: 'bar', data: receivedData, itemStyle: { color: '#0ab39c' } },
        { name: 'Remaining', type: 'bar', data: remainingData, itemStyle: { color: '#f7b84c' } }
      ]
    };
  };

  const totalItems = projectItems.length;

  const totalQty = projectItems.reduce(
    (sum, item) => sum + Number(item.pi_item_qty || 0),
    0
  );

  const totalReceived = projectItems.reduce(
    (sum, item) => sum + Number(item.pi_item_received_qty || 0),
    0
  );

  const totalRemaining = Math.max(totalQty - totalReceived, 0);

  const completionPercentage =
    totalQty > 0
      ? Math.min((totalReceived / totalQty) * 100, 100)
      : 0;
  const imageFiles = projectGallery.filter(item => item.pm_type === "IMAGE");

  if (loading) {
    return (
      <div className="main-content">
        <div className="page-content">
          <div className="container-fluid">
            <div className="d-flex justify-content-center align-items-center" style={{ height: '60vh' }}>
              <div className="spinner-border text-primary" role="status">
                <span className="visually-hidden">Loading...</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="main-content">
      <div className="page-content">
        <div className="container-fluid">
          {/* Header */}
          <div className="row mb-3 pb-1">
            <div className="col-lg-12">
              <div className="d-flex align-items-lg-center flex-lg-row flex-column">
                <div className="flex-grow-1">
                  <h4 className="fs-16 mb-1">Welcome back, {clientInfo?.profile_name || 'Client'}!</h4>
                  <p className="text-muted mb-0">
                    {project ? `Project: ${project.project_title}` : 'No active project found.'}
                  </p>
                </div>
                <div className="mt-3 mt-lg-0">
                  {project && (
                    <Link to={`/ProjectProfile/${project.project_id}`} className="btn btn-soft-info btn-sm">
                      <i className="ri-eye-line align-middle me-1" />View Project Details
                    </Link>
                  )}
                </div>
              </div>
            </div>
          </div>

          {project ? (
            <>
              {/* Summary Cards */}
              <div className="row">
                <div className="col-xl-7">
                  <div className="row">
                    <div className="col-xl-6 col-md-6">
                      <div className="card card-animate bg-info-subtle">
                        <div className="card-body">
                          <div className="d-flex align-items-center">
                            <div className="flex-grow-1">
                              <p className="text-uppercase fw-medium text-muted mb-0">Total Items</p>
                            </div>
                            <div className="avatar-sm">
                              <span className="avatar-title bg-info-subtle rounded fs-3">
                                <i className="ri-stack-line text-info fs-1" />
                              </span>
                            </div>
                          </div>
                          <div className="d-flex align-items-end justify-content-between mt-4">
                            <div><h4 className="fs-22 fw-semibold ff-secondary">{totalItems}</h4></div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="col-xl-6 col-md-6">
                      <div className="card card-animate bg-primary-subtle">
                        <div className="card-body">
                          <div className="d-flex align-items-center">
                            <div className="flex-grow-1">
                              <p className="text-uppercase fw-medium text-muted mb-0">Total Quantity</p>
                            </div>
                            <div className="avatar-sm">
                              <span className="avatar-title bg-primary-subtle rounded fs-3">
                                <i className="ri-numbers-line text-primary fs-1" />
                              </span>
                            </div>
                          </div>
                          <div className="d-flex align-items-end justify-content-between mt-4">
                            <div><h4 className="fs-22 fw-semibold ff-secondary">{totalQty.toLocaleString()}</h4></div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="col-xl-6 col-md-6">
                      <div className="card card-animate bg-success-subtle">
                        <div className="card-body">
                          <div className="d-flex align-items-center">
                            <div className="flex-grow-1">
                              <p className="text-uppercase fw-medium text-muted mb-0">Received</p>
                            </div>
                            <div className="avatar-sm">
                              <span className="avatar-title bg-success-subtle rounded fs-3">
                                <i className="ri-check-double-line text-success fs-1" />
                              </span>
                            </div>
                          </div>
                          <div className="d-flex align-items-end justify-content-between mt-4">
                            <div><h4 className="fs-22 fw-semibold ff-secondary">{totalReceived.toLocaleString()}</h4></div>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div className="col-xl-6 col-md-6">
                      <div className="card card-animate bg-warning-subtle">
                        <div className="card-body">
                          <div className="d-flex align-items-center">
                            <div className="flex-grow-1">
                              <p className="text-uppercase fw-medium text-muted mb-0">Pending</p>
                            </div>
                            <div className="avatar-sm">
                              <span className="avatar-title bg-warning-subtle rounded fs-3">
                                <i className="ri-file-list-3-line text-warning fs-1" />
                              </span>
                            </div>
                          </div>
                          <div className="d-flex align-items-end justify-content-between mt-4">
                            <div><h4 className="fs-22 fw-semibold ff-secondary">{totalRemaining.toLocaleString()}</h4></div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="col-xl-5">
                  <div className="card card-animate">
                    <div className="card-header align-items-center d-flex">
                      <h4 className="card-title mb-0 flex-grow-1">Project Information</h4>
                      <span className={`badge bg-${getProjectStatusLabel(project.project_status) === 'Active' ? 'success' : 'info'}-subtle text-${getProjectStatusLabel(project.project_status) === 'Active' ? 'success' : 'info'}`}>
                        {getProjectStatusLabel(project.project_status)}
                      </span>
                    </div>
                    <div className="card-body">
                      <div className="d-flex mb-4 align-items-center">
                        <div className="flex-shrink-0">
                          <img src={project.project_logo || "/assets/images/users/flat-design.jpg"} alt="" className="avatar-sm rounded-circle" />
                        </div>
                        <div className="flex-grow-1 ms-3">
                          <h5 className="fs-15 mb-1">{project.project_title}</h5>
                          <p className="text-muted mb-0 fs-12">{project.project_description}</p>
                        </div>
                      </div>
                      <div className="row">
                        <div className="col-4">
                          <div className="d-flex mb-2">
                            <div className="flex-shrink-0 avatar-xs align-self-center me-2">
                              <div className="avatar-title bg-light rounded-circle fs-16 text-dark"><i className="ri-calendar-check-fill" /></div>
                            </div>
                            <div><p className="mb-1 fs-12 text-muted">Start Date</p><h6 className="mb-0 fs-13">{project.project_start_date}</h6></div>
                          </div>
                        </div>
                        <div className="col-4">
                          <div className="d-flex mb-2">
                            <div className="flex-shrink-0 avatar-xs align-self-center me-2">
                              <div className="avatar-title bg-light rounded-circle fs-16 text-dark"><i className="ri-calendar-check-fill" /></div>
                            </div>
                            <div><p className="mb-1 fs-12 text-muted">End Date</p><h6 className="mb-0 fs-13">{project.project_end_date}</h6></div>
                          </div>
                        </div>
                        <div className="col-4">
                          <div className="d-flex mb-2">
                            <div className="flex-shrink-0 avatar-xs align-self-center me-2">
                              <div className="avatar-title bg-light rounded-circle fs-16 text-dark"><i className="ri-map-pin-line" /></div>
                            </div>
                            <div><p className="mb-1 fs-12 text-muted">Location</p><h6 className="mb-0 fs-13">{project.project_address}</h6></div>
                          </div>
                        </div>
                      </div>
                      <div className="border-top pt-3 mt-2">
                        <h6 className="fs-14 mb-3">Project Progress</h6>
                        <div className="mb-2">
                          <div className="d-flex justify-content-between align-items-center mb-1">
                            <p className="mb-0 fs-12">Overall Completion</p>
                            <span className="fs-12 fw-semibold">
                              {completionPercentage.toFixed(2)}%
                            </span>
                          </div>

                          <div className="progress" style={{ height: "8px" }}>
                            <div
                              className="progress-bar bg-dark"
                              role="progressbar"
                              style={{
                                width: `${completionPercentage}%`,
                                minWidth: completionPercentage > 0 ? "3px" : "0px"
                              }}
                              aria-valuenow={completionPercentage}
                              aria-valuemin="0"
                              aria-valuemax="100"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>


              {/* Project Info */}

              {/* Two Column Layout */}
              <div className="row">

                {/* Tasks - Compact Table View with Expandable Row */}
                <div className="col-xl-12">
                  <div className="card">
                    <div className="card-header align-items-center d-flex">
                      <h4 className="card-title mb-0 flex-grow-1">
                        <i className="ri-task-line me-1"></i> Project Tasks
                      </h4>
                    </div>
                    <div className="card-body p-0">
                      {projectTasks.length > 0 ? (
                        <div className="table-responsive">
                          <table className="table table-hover mb-0">
                            <thead className="table-light">
                              <tr>
                                <th style={{ width: '40px' }}></th>
                                <th>Task</th>
                                <th>Priority</th>
                                <th>Due Date</th>
                                <th>Status</th>
                                <th style={{ width: '40px' }}></th>
                              </tr>
                            </thead>
                            <tbody>
                              {projectTasks.map((task) => {
                                const priority = getTaskPriorityLabel(task.project_task_priority);
                                const taskStatus = getTaskStatusLabel(task.project_task_status);
                                const isExpanded = expandedTaskId === task.project_task_id;
                                return (
                                  <React.Fragment key={task.project_task_id}>
                                    <tr style={{ cursor: 'pointer' }} onClick={() => setExpandedTaskId(isExpanded ? null : task.project_task_id)}>
                                      <td>
                                        <i className={`ri-arrow-${isExpanded ? 'down' : 'right'}-s-line fs-5`}></i>
                                      </td>
                                      <td>
                                        <div className="fw-medium">{task.project_task_title}</div>
                                        <small className="text-muted">{task.project_task_description?.substring(0, 50)}...</small>
                                      </td>
                                      <td>
                                        <span className={`badge bg-${priority.color}-subtle text-${priority.color}`}>{priority.label}</span>
                                      </td>
                                      <td className="text-nowrap">
                                        <small>{new Date(task.project_task_due_datetime).toLocaleDateString()}</small>
                                      </td>
                                      <td>
                                        <span className={`badge bg-${taskStatus.color}-subtle text-${taskStatus.color}`}>{taskStatus.label}</span>
                                      </td>
                                      <td>
                                        {task.comments?.length > 0 && (
                                          <span className="badge bg-light text-dark">
                                            <i className="ri-chat-3-line me-1"></i>{task.comments.length}
                                          </span>
                                        )}
                                      </td>
                                    </tr>
                                    {isExpanded && (
                                      <tr>
                                        <td colSpan="6" className="p-0">
                                          <div className="p-3 bg-light">

                                            {/* Comments Section */}
                                            <div className="">
                                              <h6 className="mb-2 fs-13">
                                                <i className="ri-chat-3-line me-1"></i> Comments ({task.comments?.length || 0})
                                              </h6>
                                              {task.comments && task.comments.length > 0 ? (
                                                <div className="comments-list" style={{ maxHeight: '200px', overflowY: 'auto' }}>
                                                  {task.comments.slice().reverse().map((comment, idx) => (
                                                    <div className="d-flex mb-2" key={comment.pt_comment_id || idx}>
                                                      <div className="flex-shrink-0">
                                                        <div className="avatar-xs">
                                                          <div className="avatar-title bg-white rounded-circle">
                                                            <i className="ri-user-3-line text-primary fs-10"></i>
                                                          </div>
                                                        </div>
                                                      </div>
                                                      <div className="flex-grow-1 ms-2">
                                                        <div className="bg-white p-2 rounded">
                                                          <div className="d-flex justify-content-between align-items-center mb-1">
                                                            <strong className="fs-11">{comment.comment_created_by || 'User'}</strong>
                                                            <small className="text-muted fs-11">
                                                              {new Date(comment.pt_comment_datetime).toLocaleString()}
                                                            </small>
                                                          </div>
                                                          <p className="mb-0 fs-12">{comment.pt_comment}</p>
                                                        </div>
                                                      </div>
                                                    </div>
                                                  ))}
                                                </div>
                                              ) : (
                                                <p className="text-muted text-center py-2 mb-0 fs-12">No comments yet.</p>
                                              )}
                                            </div>
                                          </div>
                                        </td>
                                      </tr>
                                    )}
                                  </React.Fragment>
                                );
                              })}
                            </tbody>
                          </table>
                        </div>
                      ) : (
                        <div className="text-center py-4">
                          <i className="ri-task-line fs-1 text-muted"></i>
                          <p className="text-muted mb-0 mt-2">No tasks assigned yet.</p>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              </div>

              {/* Charts Row */}
              <div className="row mt-3">
                <div className="col-xl-12">
                  <div className="card">
                    <div className="card-header align-items-center d-flex">
                      <h4 className="card-title mb-0 flex-grow-1">Item Quantity Overview</h4>
                    </div>
                    <div className="card-body">
                      <ReactECharts option={getItemChartOption()} style={{ height: '400px' }} />
                    </div>
                  </div>
                </div>
              </div>

              {/* Gallery Section */}
              {imageFiles.length > 0 && (
                <div className="row mt-4">
                  <div className="col-12">
                    <div className="card border-0 shadow-sm overflow-hidden">

                      <div className="card-header bg-white border-0 d-flex align-items-center justify-content-between py-3">
                        <div>
                          <h4 className="card-title mb-0 fw-semibold">
                            <i className="ri-image-2-line me-2 text-primary"></i>
                            Project Gallery
                          </h4>
                        </div>
                      </div>

                      <div className="card-body">
                        <div className="row g-4">
                          {imageFiles.map((img, idx) => (
                            <div
                              className="col-xl-3 col-lg-4 col-md-6"
                              key={img.project_media_id || idx}
                            >
                              <div
                                className="gallery-card position-relative overflow-hidden rounded-4"
                                onClick={() =>
                                  window.open(
                                    `${imageURL}${img.pm_file_name}`,
                                    "_blank"
                                  )
                                }
                                style={{
                                  cursor: "pointer",
                                  height: "240px",
                                }}
                              >
                                <img
                                  src={`${imageURL}${img.pm_file_name}`}
                                  alt={img.pm_title || "Gallery Image"}
                                  className="w-100 h-100"
                                  style={{
                                    objectFit: "cover",
                                    transition: "0.4s ease",
                                  }}
                                  onError={(e) => {
                                    e.target.src =
                                      "/assets/images/placeholder-image.jpg";
                                  }}
                                />

                                {/* Overlay */}
                                <div
                                  className="position-absolute top-0 start-0 w-100 h-100 d-flex flex-column justify-content-end p-3"
                                  style={{
                                    background:
                                      "linear-gradient(to top, rgba(0,0,0,0.75), rgba(0,0,0,0.1))",
                                  }}
                                >
                                  <div className="text-white">
                                    <h6 className="mb-1 text-truncate fw-semibold">
                                      {img.pm_title || "Project Image"}
                                    </h6>

                                    <small className="opacity-75">
                                      Click to preview
                                    </small>
                                  </div>
                                </div>

                                {/* Hover Icon */}
                                <div
                                  className="position-absolute top-0 end-0 m-3 d-flex align-items-center justify-content-center rounded-circle"
                                  style={{
                                    width: "42px",
                                    height: "42px",
                                    background: "rgba(255,255,255,0.2)",
                                    backdropFilter: "blur(6px)",
                                  }}
                                >
                                  <i className="ri-eye-line text-white fs-5"></i>
                                </div>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="row">
              <div className="col-12">
                <div className="card">
                  <div className="card-body text-center py-5">
                    <div className="avatar-md mx-auto mb-3">
                      <div className="avatar-title bg-light rounded-circle fs-2">
                        <i className="ri-building-line text-muted" />
                      </div>
                    </div>
                    <h5>No Project Found</h5>
                    <p className="text-muted">You don't have any active projects at the moment.</p>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default Dashboard;