import React, { useState, useEffect } from 'react';
import { DollarSign, TrendingUp, Search, Filter, ArrowUpDown } from 'lucide-react';

interface CompensationData {
  employeeId: string;
  employeeName: string;
  title: string;
  department: string;
  baseSalary: number;
  bonus?: number;
  equity?: number;
  totalComp: number;
  flsaStatus: string;
  paymentUnit: string;
  lastRaise?: { date: string; amount: number };
}

type SortField = 'employeeName' | 'title' | 'baseSalary' | 'totalComp' | 'department';

export default function CompensationGrid() {
  const [compensations, setCompensations] = useState<CompensationData[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [departmentFilter, setDepartmentFilter] = useState('all');
  const [sortField, setSortField] = useState<SortField>('totalComp');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');

  useEffect(() => {
    // Mock data - in production, fetch from Gusto MCP
    setCompensations([
      {
        employeeId: '1',
        employeeName: 'Sarah Johnson',
        title: 'Senior Software Engineer',
        department: 'Engineering',
        baseSalary: 145000,
        bonus: 20000,
        equity: 50000,
        totalComp: 215000,
        flsaStatus: 'Exempt',
        paymentUnit: 'Year',
        lastRaise: { date: '2024-01-01', amount: 15000 }
      },
      {
        employeeId: '2',
        employeeName: 'Michael Chen',
        title: 'Product Manager',
        department: 'Product',
        baseSalary: 135000,
        bonus: 25000,
        equity: 40000,
        totalComp: 200000,
        flsaStatus: 'Exempt',
        paymentUnit: 'Year',
        lastRaise: { date: '2023-12-15', amount: 12000 }
      },
      {
        employeeId: '3',
        employeeName: 'Emily Rodriguez',
        title: 'Marketing Director',
        department: 'Marketing',
        baseSalary: 125000,
        bonus: 18000,
        equity: 35000,
        totalComp: 178000,
        flsaStatus: 'Exempt',
        paymentUnit: 'Year'
      },
      {
        employeeId: '4',
        employeeName: 'David Kim',
        title: 'Sales Representative',
        department: 'Sales',
        baseSalary: 75000,
        bonus: 30000,
        totalComp: 105000,
        flsaStatus: 'Exempt',
        paymentUnit: 'Year',
        lastRaise: { date: '2024-01-15', amount: 5000 }
      },
      {
        employeeId: '5',
        employeeName: 'Lisa Wang',
        title: 'UI/UX Designer',
        department: 'Design',
        baseSalary: 110000,
        bonus: 15000,
        equity: 25000,
        totalComp: 150000,
        flsaStatus: 'Exempt',
        paymentUnit: 'Year'
      },
      {
        employeeId: '6',
        employeeName: 'James Wilson',
        title: 'DevOps Engineer',
        department: 'Engineering',
        baseSalary: 140000,
        bonus: 18000,
        equity: 45000,
        totalComp: 203000,
        flsaStatus: 'Exempt',
        paymentUnit: 'Year'
      }
    ]);
  }, []);

  const departments = [...new Set(compensations.map(c => c.department))];

  const filteredAndSorted = compensations
    .filter(comp => {
      const matchesSearch = comp.employeeName.toLowerCase().includes(searchQuery.toLowerCase()) ||
                           comp.title.toLowerCase().includes(searchQuery.toLowerCase());
      const matchesDept = departmentFilter === 'all' || comp.department === departmentFilter;
      return matchesSearch && matchesDept;
    })
    .sort((a, b) => {
      const aVal = a[sortField];
      const bVal = b[sortField];
      const multiplier = sortOrder === 'asc' ? 1 : -1;
      
      if (typeof aVal === 'string' && typeof bVal === 'string') {
        return multiplier * aVal.localeCompare(bVal);
      }
      return multiplier * ((aVal as number) - (bVal as number));
    });

  const toggleSort = (field: SortField) => {
    if (sortField === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortField(field);
      setSortOrder('desc');
    }
  };

  const avgSalary = compensations.reduce((sum, c) => sum + c.baseSalary, 0) / compensations.length;
  const avgTotal = compensations.reduce((sum, c) => sum + c.totalComp, 0) / compensations.length;
  const totalPayroll = compensations.reduce((sum, c) => sum + c.totalComp, 0);

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 p-8">
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <h1 className="text-4xl font-bold mb-2 flex items-center gap-3">
            <DollarSign className="text-emerald-400" size={36} />
            Compensation Grid
          </h1>
          <p className="text-slate-400">Employee compensation breakdown across the organization</p>
        </div>

        {/* Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
          <div className="bg-slate-900 rounded-lg p-6 border border-slate-800">
            <div className="text-slate-400 text-sm mb-2">Average Base Salary</div>
            <div className="text-3xl font-bold text-blue-400">
              ${(avgSalary / 1000).toFixed(0)}k
            </div>
          </div>
          <div className="bg-slate-900 rounded-lg p-6 border border-slate-800">
            <div className="text-slate-400 text-sm mb-2">Average Total Comp</div>
            <div className="text-3xl font-bold text-emerald-400">
              ${(avgTotal / 1000).toFixed(0)}k
            </div>
          </div>
          <div className="bg-slate-900 rounded-lg p-6 border border-slate-800">
            <div className="text-slate-400 text-sm mb-2">Total Annual Payroll</div>
            <div className="text-3xl font-bold text-purple-400">
              ${(totalPayroll / 1000000).toFixed(2)}M
            </div>
          </div>
        </div>

        {/* Filters */}
        <div className="bg-slate-900 rounded-lg p-6 mb-6 border border-slate-800">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-slate-400" size={20} />
              <input
                type="text"
                placeholder="Search by name or title..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-3 bg-slate-800 border border-slate-700 rounded-lg focus:outline-none focus:border-blue-500 text-slate-100"
              />
            </div>
            <select
              value={departmentFilter}
              onChange={(e) => setDepartmentFilter(e.target.value)}
              className="px-4 py-3 bg-slate-800 border border-slate-700 rounded-lg focus:outline-none focus:border-blue-500 text-slate-100"
            >
              <option value="all">All Departments</option>
              {departments.map(dept => (
                <option key={dept} value={dept}>{dept}</option>
              ))}
            </select>
          </div>
        </div>

        {/* Compensation Table */}
        <div className="bg-slate-900 rounded-lg border border-slate-800 overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-800/50">
                <tr>
                  <SortHeader field="employeeName" label="Employee" sortField={sortField} sortOrder={sortOrder} onSort={toggleSort} />
                  <SortHeader field="title" label="Title" sortField={sortField} sortOrder={sortOrder} onSort={toggleSort} />
                  <SortHeader field="department" label="Department" sortField={sortField} sortOrder={sortOrder} onSort={toggleSort} />
                  <SortHeader field="baseSalary" label="Base Salary" sortField={sortField} sortOrder={sortOrder} onSort={toggleSort} align="right" />
                  <th className="px-6 py-4 text-right text-sm font-medium text-slate-400">Bonus</th>
                  <th className="px-6 py-4 text-right text-sm font-medium text-slate-400">Equity</th>
                  <SortHeader field="totalComp" label="Total Comp" sortField={sortField} sortOrder={sortOrder} onSort={toggleSort} align="right" />
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-800">
                {filteredAndSorted.map(comp => (
                  <tr key={comp.employeeId} className="hover:bg-slate-800/30">
                    <td className="px-6 py-4">
                      <div className="font-medium">{comp.employeeName}</div>
                      {comp.lastRaise && (
                        <div className="text-xs text-green-400 flex items-center gap-1 mt-1">
                          <TrendingUp size={12} />
                          +${(comp.lastRaise.amount / 1000).toFixed(0)}k on {comp.lastRaise.date}
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 text-slate-300">{comp.title}</td>
                    <td className="px-6 py-4 text-slate-300">{comp.department}</td>
                    <td className="px-6 py-4 text-right font-medium">${comp.baseSalary.toLocaleString()}</td>
                    <td className="px-6 py-4 text-right text-yellow-400">
                      {comp.bonus ? `$${comp.bonus.toLocaleString()}` : '-'}
                    </td>
                    <td className="px-6 py-4 text-right text-purple-400">
                      {comp.equity ? `$${comp.equity.toLocaleString()}` : '-'}
                    </td>
                    <td className="px-6 py-4 text-right font-bold text-emerald-400">
                      ${comp.totalComp.toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

function SortHeader({ field, label, sortField, sortOrder, onSort, align = 'left' }: {
  field: SortField;
  label: string;
  sortField: SortField;
  sortOrder: 'asc' | 'desc';
  onSort: (field: SortField) => void;
  align?: 'left' | 'right';
}) {
  const isActive = sortField === field;
  
  return (
    <th
      className={`px-6 py-4 text-${align} text-sm font-medium text-slate-400 cursor-pointer hover:text-slate-200 transition-colors`}
      onClick={() => onSort(field)}
    >
      <div className={`flex items-center gap-2 ${align === 'right' ? 'justify-end' : ''}`}>
        {label}
        <ArrowUpDown size={14} className={isActive ? 'text-blue-400' : 'text-slate-600'} />
      </div>
    </th>
  );
}
