import React, { useState, useEffect } from "react";
import { useTheme } from "../contexts/ThemeContext";
import EmployeeLogHeader from "../components/EmployeeLog/EmployeeLogHeader";
import SummaryCards from "../components/EmployeeLog/SummaryCards";
import ActivityLogTable from "../components/EmployeeLog/ActivityLogTable";
import {
  FaCalendarAlt,
  FaSearch,
  FaTimes,
  FaDownload,
  FaSpinner,
} from "react-icons/fa";
import * as XLSX from "xlsx";
import { formatIST, formatDateIndian } from "../utils/timeUtils";
import { buildApiUrl, API_ENDPOINTS } from "../utils/config";

const EmployeeLogPage = () => {
  const { isLight } = useTheme();
  const [employeeLogData, setEmployeeLogData] = useState([]);
  const [filteredData, setFilteredData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [dateRange, setDateRange] = useState("all_time");
  const [searchTerm, setSearchTerm] = useState("");

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  // Helper function to format project names for display
  const formatProjectNames = (projectNames) => {
    if (!projectNames || projectNames === "no_projects") {
      return "No Projects";
    }
    return projectNames;
  };

  // Theme-based styling
  const cardBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-md hover:shadow-lg"
    : "bg-slate-800 border border-slate-700 shadow-xl hover:shadow-2xl";

  const textClass = isLight ? "text-amber-700" : "text-slate-300";

  const inputClass = isLight
    ? "bg-white text-gray-900 border-gray-300 focus:ring-amber-500 focus:border-amber-500"
    : "bg-slate-700 text-slate-100 border-slate-600 focus:ring-cyan-400 focus:border-cyan-400 hover:border-slate-500";

  const buttonClass = isLight
    ? "bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white"
    : "bg-blue-600 hover:bg-blue-700 text-white shadow-lg";

  // Map API data to table format
  const mapApiDataToTableFormat = (apiLogs) => {
    return apiLogs.map((log) => ({
      id: log.log_id,
      user_id: log.user_id,
      employee: log.employee_name,
      division: log.division_name,
      role: log.role_name,
      projects: log.project_names,
      action: log.action,
      timestamp: formatIST(log.created_at),
      remarks: log.remarks,
    }));
  };

  // Search functionality
  const filterDataBySearch = (data, searchTerm) => {
    if (!searchTerm.trim()) return data;

    const searchLower = searchTerm.toLowerCase();
    return data.filter(
      (log) =>
        (log.employee && log.employee.toLowerCase().includes(searchLower)) ||
        (log.division && log.division.toLowerCase().includes(searchLower)) ||
        (log.role && log.role.toLowerCase().includes(searchLower)) ||
        (log.action && log.action.toLowerCase().includes(searchLower)) ||
        (log.remarks && log.remarks.toLowerCase().includes(searchLower)) ||
        (log.projects && log.projects.toLowerCase().includes(searchLower)) ||
        (log.user_id && log.user_id.toString().includes(searchLower)) ||
        (log.id && log.id.toString().includes(searchLower))
    );
  };

  // Apply search filter whenever search term or data changes
  useEffect(() => {
    const filtered = filterDataBySearch(employeeLogData, searchTerm);
    setFilteredData(filtered);
    setCurrentPage(1); // Reset to first page when search changes
  }, [searchTerm, employeeLogData]);

  // Pagination calculations - now using filteredData instead of employeeLogData
  const totalPages = Math.ceil(filteredData.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentEmployeeLogs = filteredData.slice(startIndex, endIndex);

  // Reset to first page when filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [startDate, endDate]);

  // Pagination functions
  const goToPage = (page) => {
    setCurrentPage(page);
  };

  const goToPrevious = () => {
    setCurrentPage((prev) => Math.max(prev - 1, 1));
  };

  const goToNext = () => {
    setCurrentPage((prev) => Math.min(prev + 1, totalPages));
  };

  // Fetch employee logs
  const fetchEmployeeLogs = async (start = "", end = "") => {
    try {
      setLoading(true);
      setError(null);

      let url;
      let params = new URLSearchParams();

      // If no dates provided, use the all_employee_logs endpoint
      if (!start && !end) {
        url = buildApiUrl(API_ENDPOINTS.ALL_EMPLOYEE_LOGS);
      } else {
        url = buildApiUrl(API_ENDPOINTS.EMPLOYEE_LOGS_BY_DATE);
        params.append("start_date", start);
        params.append("end_date", end);
      }

      const response = await fetch(`${url}?${params.toString()}`);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data && Array.isArray(data)) {
        const formattedData = mapApiDataToTableFormat(data);
        setEmployeeLogData(formattedData);
      } else {
        setEmployeeLogData([]);
      }
    } catch (err) {
      setError(err.message);
      setEmployeeLogData([]);
    } finally {
      setLoading(false);
    }
  };

  // Initial load - fetch all data
  useEffect(() => {
    fetchEmployeeLogs();
  }, []);

  const clearFilters = () => {
    setStartDate("");
    setEndDate("");
    setSearchTerm("");
    fetchEmployeeLogs();
  };

  const downloadCSV = () => {
    if (filteredData.length === 0) return;

    const csvData = filteredData.map((log) => ({
      "Log ID": log.id,
      "User ID": log.user_id,
      Employee: log.employee,
      Division: log.division,
      Role: log.role,
      Projects: formatProjectNames(log.projects),
      Action: log.action,
      Timestamp: log.timestamp,
      Remarks: log.remarks,
    }));

    const ws = XLSX.utils.json_to_sheet(csvData);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "Employee Logs");

    let filename = "employee_logs";
    if (
      typeof dateRange === "object" &&
      dateRange.start_date &&
      dateRange.end_date
    ) {
      filename += `_${dateRange.start_date}_to_${dateRange.end_date}`;
    } else if (dateRange === "all_time") {
      filename += "_all_time";
    }
    if (searchTerm) {
      filename += `_search_${searchTerm.replace(/[^a-zA-Z0-9]/g, "_")}`;
    }
    filename += ".xlsx";

    XLSX.writeFile(wb, filename);
  };

  return (
    <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
      {/* Header */}
      <EmployeeLogHeader />

      {/* Summary Cards */}
      <SummaryCards />

      {/* Search and Filter Section */}
      <div
        className={`${cardBgClass} rounded-xl p-3 sm:p-6 transition-all duration-300`}
      >
        {/* Search Bar */}
        <div className="mb-4 sm:mb-6">
          <label className={`block text-sm font-medium ${textClass} mb-2`}>
            Search Employee Logs
          </label>
          <div className="relative">
            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
              <FaSearch
                className={`h-4 w-4 ${
                  isLight ? "text-gray-400" : "text-slate-400"
                }`}
              />
            </div>
            <input
              type="text"
              placeholder="Search by employee name, division, role, action, remarks, projects, or ID..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className={`w-full pl-10 pr-4 py-3 sm:py-2 rounded-xl sm:rounded-md border text-sm transition-all duration-200 ${
                isLight 
                  ? 'border-gray-200 bg-white text-gray-900 focus:ring-2 focus:ring-amber-500 focus:border-amber-500 hover:border-gray-300' 
                  : 'border-slate-600 bg-slate-700 text-slate-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 hover:border-slate-500'
              } ${inputClass}`}
              disabled={loading}
            />
            {searchTerm && (
              <button
                onClick={() => setSearchTerm("")}
                className={`absolute inset-y-0 right-0 pr-3 flex items-center ${
                  isLight
                    ? "text-gray-400 hover:text-gray-600"
                    : "text-slate-400 hover:text-slate-300"
                }`}
              >
                <FaTimes className="h-4 w-4" />
              </button>
            )}
          </div>
          {searchTerm && (
            <p
              className={`mt-2 text-xs ${
                isLight ? "text-gray-600" : "text-slate-400"
              }`}
            >
              Found {filteredData.length} results for "{searchTerm}"
            </p>
          )}
        </div>

        {/* Date Range Filter */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
          <div className="flex-1 grid grid-cols-1 gap-4 sm:grid-cols-2">
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                Start Date
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <FaCalendarAlt className={`h-4 w-4 ${
                    isLight ? 'text-gray-400' : 'text-slate-400'
                  }`} />
                </div>
                <input
                  type="date"
                  value={startDate}
                  onChange={(e) => {
                    setStartDate(e.target.value);
                    if (e.target.value && endDate) {
                      fetchEmployeeLogs(e.target.value, endDate);
                    }
                  }}
                  className={`w-full pl-10 pr-3 py-3 sm:py-2 rounded-xl sm:rounded-md border text-sm transition-all duration-200 ${
                    isLight 
                      ? 'border-gray-200 bg-white text-gray-900 focus:ring-2 focus:ring-amber-500 focus:border-amber-500 hover:border-gray-300' 
                      : 'border-slate-600 bg-slate-700 text-slate-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 hover:border-slate-500'
                  } ${inputClass}`}
                  disabled={loading}
                />
              </div>
            </div>
            <div>
              <label className={`block text-sm font-medium ${textClass} mb-2`}>
                End Date
              </label>
              <div className="relative">
                <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                  <FaCalendarAlt className={`h-4 w-4 ${
                    isLight ? 'text-gray-400' : 'text-slate-400'
                  }`} />
                </div>
                <input
                  type="date"
                  value={endDate}
                  onChange={(e) => {
                    setEndDate(e.target.value);
                    if (startDate && e.target.value) {
                      fetchEmployeeLogs(startDate, e.target.value);
                    }
                  }}
                  className={`w-full pl-10 pr-3 py-3 sm:py-2 rounded-xl sm:rounded-md border text-sm transition-all duration-200 ${
                    isLight 
                      ? 'border-gray-200 bg-white text-gray-900 focus:ring-2 focus:ring-amber-500 focus:border-amber-500 hover:border-gray-300' 
                      : 'border-slate-600 bg-slate-700 text-slate-100 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 hover:border-slate-500'
                  } ${inputClass}`}
                  disabled={loading}
                />
              </div>
            </div>
          </div>

          <div className="flex items-center justify-between gap-3 w-full sm:w-auto sm:justify-end">
            {/* Left side buttons */}
            <div className="flex items-center gap-3">
              <button
                onClick={clearFilters}
                disabled={loading}
                className={`px-4 py-3 sm:py-2 rounded-xl sm:rounded-md font-medium text-sm transition-all duration-200 border ${
                  isLight
                    ? "border-yellow-300 text-amber-700 hover:bg-yellow-50 bg-white hover:border-yellow-400 hover:shadow-md"
                    : "border-slate-600 text-slate-300 hover:bg-slate-700 bg-slate-800 hover:border-slate-500 hover:shadow-md"
                } disabled:opacity-50 disabled:cursor-not-allowed`}
              >
                <div className="flex items-center gap-2">
                  <FaTimes className="h-3 w-3" />
                  <span>Clear Filters</span>
                </div>
              </button>
            </div>

            {/* Right side download button */}
            <div className="relative group flex-shrink-0 self-center">
              {/* Mobile download button - Full button with text */}
              <button
                onClick={downloadCSV}
                disabled={loading || !filteredData.length}
                className={`px-4 py-3 sm:py-2 rounded-xl sm:rounded-md font-medium text-sm transition-all duration-200 hover:scale-105 disabled:opacity-50 disabled:cursor-not-allowed ${
                  isLight
                    ? "bg-green-500 hover:bg-green-600 text-white shadow-md hover:shadow-lg"
                    : "bg-green-600 hover:bg-green-700 text-white shadow-md hover:shadow-lg"
                } md:hidden`}
                title="Download Excel File"
              >
                <div className="flex items-center gap-2">
                  <FaDownload className="h-3 w-3" />
                  <span>Download</span>
                </div>
              </button>
              
              {/* Desktop download button - Circular icon button */}
              <button
                onClick={downloadCSV}
                disabled={loading || !filteredData.length}
                className={`w-8 h-8 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110 disabled:opacity-50 disabled:cursor-not-allowed ${
                  isLight
                    ? "bg-green-500 hover:bg-green-600 text-white"
                    : "bg-green-600 hover:bg-green-700 text-white"
                } hidden md:flex`}
                title="Download Excel File"
              >
                <FaDownload className="text-xs" />
              </button>

              {/* Responsive Tooltip - Show on both mobile and desktop */}
              <div
                className={`absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 rounded-lg text-xs font-medium opacity-0 group-hover:opacity-100 transition-all duration-300 pointer-events-none z-30 ${
                  isLight
                    ? "bg-gray-900 text-white shadow-xl"
                    : "bg-white text-gray-900 shadow-xl border border-gray-300"
                } whitespace-nowrap`}
              >
                Download Excel
                {/* Tooltip Arrow */}
                <div
                  className={`absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent ${
                    isLight ? "border-t-gray-900" : "border-t-white"
                  }`}
                ></div>
              </div>
            </div>
          </div>
        </div>

        {/* Filter Info - Only show when filter is applied */}
        {(startDate || endDate || searchTerm) && (
          <div
            className={`mt-4 p-3 rounded-lg border ${
              isLight
                ? "bg-yellow-50 border-yellow-200"
                : "bg-slate-700 border-slate-600"
            }`}
          >
            <p className={`text-sm ${textClass}`}>
              <strong>Current Filter:</strong>{" "}
              {startDate && endDate
                ? `Showing logs from ${formatDateIndian(startDate)} to ${formatDateIndian(endDate)}`
                : startDate
                ? `Showing logs from ${formatDateIndian(startDate)} onwards`
                : endDate
                ? `Showing logs up to ${formatDateIndian(endDate)}`
                : ""}
              {searchTerm && (startDate || endDate) && " and "}
              {searchTerm && `Searching for "${searchTerm}"`}
              {!startDate &&
                !endDate &&
                searchTerm &&
                `Searching for "${searchTerm}"`}
            </p>
          </div>
        )}
      </div>

      {/* Error Message */}
      {error && (
        <div
          className={`rounded-lg p-4 ${
            isLight
              ? "bg-red-50 border border-red-200 text-red-800"
              : "bg-red-900/20 border border-red-700 text-red-300"
          }`}
        >
          <p className="text-sm">{error}</p>
        </div>
      )}

      {/* Activity Log Table */}
      <ActivityLogTable
        employeeLogData={currentEmployeeLogs}
        loading={loading}
        error={error}
        currentPage={currentPage}
        totalPages={totalPages}
        startIndex={startIndex}
        endIndex={endIndex}
        goToPage={goToPage}
        goToPrevious={goToPrevious}
        goToNext={goToNext}
      />
    </div>
  );
};

export default EmployeeLogPage;
