import React, { useState, useMemo } from "react";
import { FaFileAlt, FaDownload, FaTrash, FaIdCard, FaProjectDiagram, FaSortNumericDown } from "react-icons/fa";
import { useTheme } from "../../contexts/ThemeContext";

const FormsTable = ({ kickoffForms, onDownload, onDelete }) => {
  const { isLight } = useTheme();
  const [sortOrder, setSortOrder] = useState('asc'); // 'asc' or 'desc'

  const cardBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-md hover:shadow-lg"
    : "bg-gradient-to-br from-gray-800 to-slate-800 border border-gray-700 shadow-lg hover:shadow-xl";

  const headingClass = isLight ? "text-amber-800" : "text-gray-100";
  const textClass = isLight ? "text-gray-700" : "text-gray-300";
  const labelClass = isLight ? "text-amber-600" : "text-amber-400";

  // Sort forms by ID in ascending order
  const sortedForms = useMemo(() => {
    if (!Array.isArray(kickoffForms)) return [];
    
    return [...kickoffForms].sort((a, b) => {
      const idA = parseInt(a.id) || 0;
      const idB = parseInt(b.id) || 0;
      return sortOrder === 'asc' ? idA - idB : idB - idA;
    });
  }, [kickoffForms, sortOrder]);

  const toggleSortOrder = () => {
    setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc');
  };

  const renderFormCard = (form) => {
    if (!form || typeof form !== 'object') return null;

    const safeId = String(form.id || 'N/A');
    const safeProjectType = String(form.project_type || 'Unknown');

    return (
      <div 
        key={safeId} 
        className={`${cardBgClass} rounded-xl p-6 transition-all duration-300 hover:scale-105`}
      >
        {/* Card Header */}
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center space-x-3">
            <div className={`w-10 h-10 rounded-full flex items-center justify-center ${
              isLight ? "bg-amber-100" : "bg-amber-900"
            }`}>
              <FaFileAlt className={`w-5 h-5 ${isLight ? "text-amber-600" : "text-amber-300"} flex-shrink-0`} />
            </div>
            <div>
              <h3 className={`text-lg font-semibold ${headingClass}`}>Form #{safeId}</h3>
              <p className={`text-sm ${textClass}`}>Kick-off Form</p>
            </div>
          </div>
        </div>

        {/* Card Content */}
        <div className="space-y-4">
          {/* ID Section */}
          <div className="flex items-center space-x-3">
            <FaIdCard className={`w-4 h-4 ${labelClass} flex-shrink-0`} />
            <div>
              <p className={`text-xs font-medium uppercase tracking-wider ${labelClass}`}>Form ID</p>
              <p className={`text-sm font-semibold ${textClass}`}>{safeId}</p>
            </div>
          </div>

          {/* Project Type Section */}
          <div className="flex items-center space-x-3">
            <FaProjectDiagram className={`w-4 h-4 ${labelClass} flex-shrink-0`} />
            <div>
              <p className={`text-xs font-medium uppercase tracking-wider ${labelClass}`}>Project Type</p>
              <p className={`text-sm font-semibold ${textClass}`}>{safeProjectType}</p>
            </div>
          </div>
        </div>

        {/* Card Actions */}
        <div className="flex items-center justify-center space-x-3 mt-6 pt-4 border-t border-gray-200">
          <button 
            onClick={() => onDownload(safeId)}
            className="bg-purple-100 hover:bg-purple-200 text-purple-700 hover:text-purple-800 px-4 py-2 rounded-lg border border-purple-300 hover:border-purple-400 transition-all duration-200 hover:scale-105 shadow-sm hover:shadow-md flex items-center justify-center space-x-2 flex-1" 
            title="Download Form"
          >
            <FaDownload className="w-4 h-4 flex-shrink-0" />
            <span className="text-sm font-medium">Download</span>
          </button>
          <button 
            onClick={() => onDelete(safeId)}
            className="bg-red-100 hover:bg-red-200 text-red-700 hover:text-red-800 px-4 py-2 rounded-lg border border-red-300 hover:border-red-400 transition-all duration-200 hover:scale-105 shadow-sm hover:shadow-md flex items-center justify-center space-x-2 flex-1" 
            title="Delete Form"
          >
            <FaTrash className="w-4 h-4 flex-shrink-0" />
            <span className="text-sm font-medium">Delete</span>
          </button>
        </div>
      </div>
    );
  };

  const safeKickoffForms = Array.isArray(kickoffForms) ? kickoffForms : [];

  return (
    <div className="space-y-6">
      {/* Sort Header */}
      {safeKickoffForms.length > 0 && (
        <div className={`${cardBgClass} rounded-xl p-4`}>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <FaSortNumericDown className={`w-5 h-5 ${labelClass} flex-shrink-0`} />
              <span className={`text-sm font-medium ${headingClass}`}>
                Forms sorted by ID ({sortedForms.length} total)
              </span>
            </div>
            <button
              onClick={toggleSortOrder}
              className={`px-3 py-2 rounded-lg border transition-all duration-200 hover:scale-105 flex items-center justify-center ${
                isLight 
                  ? "bg-amber-100 hover:bg-amber-200 text-amber-700 border-amber-300 hover:border-amber-400"
                  : "bg-amber-900 hover:bg-amber-800 text-amber-300 border-amber-600 hover:border-amber-500"
              }`}
              title={`Currently sorted ${sortOrder === 'asc' ? 'ascending' : 'descending'}. Click to toggle.`}
            >
              <span className="text-sm font-medium">
                {sortOrder === 'asc' ? '↑ Ascending' : '↓ Descending'}
              </span>
            </button>
          </div>
        </div>
      )}

      {/* Cards Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        {sortedForms.map((form) => renderFormCard(form))}
      </div>
      
      {/* Empty State */}
      {safeKickoffForms.length === 0 && (
        <div className={`${cardBgClass} rounded-xl p-12 text-center`}>
          <FaFileAlt className={`mx-auto h-16 w-16 ${isLight ? "text-gray-300" : "text-gray-500"} mb-4 flex-shrink-0`} />
          <h3 className={`text-lg font-medium ${headingClass} mb-2`}>No forms submitted</h3>
          <p className={`text-sm ${textClass}`}>Get started by submitting your first kick-off form.</p>
        </div>
      )}
    </div>
  );
};

export default FormsTable;
