import React, { useState, useEffect } from 'react';
import { Umbrella, TrendingUp, Users, Clock } from 'lucide-react';

interface EmployeeBalance {
  employeeId: string;
  employeeName: string;
  department: string;
  balances: {
    vacation: { accrued: number; used: number; remaining: number };
    sick: { accrued: number; used: number; remaining: number };
    personal: { accrued: number; used: number; remaining: number };
  };
}

export default function TimeOffBalances() {
  const [balances, setBalances] = useState<EmployeeBalance[]>([]);
  const [selectedType, setSelectedType] = useState<'vacation' | 'sick' | 'personal'>('vacation');

  useEffect(() => {
    // Mock data - in production, fetch from Gusto MCP
    setBalances([
      {
        employeeId: '1',
        employeeName: 'Sarah Johnson',
        department: 'Engineering',
        balances: {
          vacation: { accrued: 120, used: 40, remaining: 80 },
          sick: { accrued: 80, used: 16, remaining: 64 },
          personal: { accrued: 40, used: 8, remaining: 32 }
        }
      },
      {
        employeeId: '2',
        employeeName: 'Michael Chen',
        department: 'Product',
        balances: {
          vacation: { accrued: 120, used: 24, remaining: 96 },
          sick: { accrued: 80, used: 24, remaining: 56 },
          personal: { accrued: 40, used: 16, remaining: 24 }
        }
      },
      {
        employeeId: '3',
        employeeName: 'Emily Rodriguez',
        department: 'Marketing',
        balances: {
          vacation: { accrued: 100, used: 30, remaining: 70 },
          sick: { accrued: 60, used: 8, remaining: 52 },
          personal: { accrued: 32, used: 4, remaining: 28 }
        }
      },
      {
        employeeId: '4',
        employeeName: 'David Kim',
        department: 'Sales',
        balances: {
          vacation: { accrued: 80, used: 20, remaining: 60 },
          sick: { accrued: 60, used: 12, remaining: 48 },
          personal: { accrued: 32, used: 8, remaining: 24 }
        }
      },
      {
        employeeId: '5',
        employeeName: 'Lisa Wang',
        department: 'Design',
        balances: {
          vacation: { accrued: 100, used: 56, remaining: 44 },
          sick: { accrued: 60, used: 0, remaining: 60 },
          personal: { accrued: 32, used: 12, remaining: 20 }
        }
      }
    ]);
  }, []);

  const totalStats = balances.reduce(
    (acc, emp) => {
      const balance = emp.balances[selectedType];
      return {
        accrued: acc.accrued + balance.accrued,
        used: acc.used + balance.used,
        remaining: acc.remaining + balance.remaining
      };
    },
    { accrued: 0, used: 0, remaining: 0 }
  );

  const avgUsageRate = (totalStats.used / totalStats.accrued) * 100;

  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">
            <Clock className="text-purple-400" size={36} />
            Time Off Balances
          </h1>
          <p className="text-slate-400">Employee time off balance overview per policy</p>
        </div>

        {/* Type Selector */}
        <div className="bg-slate-900 rounded-lg p-6 mb-6 border border-slate-800">
          <div className="flex gap-2">
            {(['vacation', 'sick', 'personal'] as const).map(type => (
              <button
                key={type}
                onClick={() => setSelectedType(type)}
                className={`px-6 py-3 rounded-lg font-medium transition-colors capitalize ${
                  selectedType === type
                    ? 'bg-blue-600 text-white'
                    : 'bg-slate-800 text-slate-300 hover:bg-slate-700'
                }`}
              >
                {type} Time
              </button>
            ))}
          </div>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
          <StatCard
            title="Total Accrued"
            value={`${totalStats.accrued}h`}
            icon={<TrendingUp className="text-blue-400" />}
          />
          <StatCard
            title="Total Used"
            value={`${totalStats.used}h`}
            icon={<Umbrella className="text-cyan-400" />}
          />
          <StatCard
            title="Total Remaining"
            value={`${totalStats.remaining}h`}
            icon={<Clock className="text-emerald-400" />}
          />
          <StatCard
            title="Usage Rate"
            value={`${avgUsageRate.toFixed(0)}%`}
            icon={<Users className="text-purple-400" />}
          />
        </div>

        {/* Balances Table */}
        <div className="bg-slate-900 rounded-lg border border-slate-800 overflow-hidden">
          <div className="p-6 border-b border-slate-800">
            <h2 className="text-xl font-semibold capitalize">{selectedType} Time Balances</h2>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-800/50">
                <tr>
                  <th className="px-6 py-4 text-left text-sm font-medium text-slate-400">Employee</th>
                  <th className="px-6 py-4 text-left text-sm font-medium text-slate-400">Department</th>
                  <th className="px-6 py-4 text-right text-sm font-medium text-slate-400">Accrued</th>
                  <th className="px-6 py-4 text-right text-sm font-medium text-slate-400">Used</th>
                  <th className="px-6 py-4 text-right text-sm font-medium text-slate-400">Remaining</th>
                  <th className="px-6 py-4 text-right text-sm font-medium text-slate-400">Usage %</th>
                  <th className="px-6 py-4 text-center text-sm font-medium text-slate-400">Progress</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-800">
                {balances.map(emp => {
                  const balance = emp.balances[selectedType];
                  const usagePercent = (balance.used / balance.accrued) * 100;
                  
                  return (
                    <tr key={emp.employeeId} className="hover:bg-slate-800/30">
                      <td className="px-6 py-4 font-medium">{emp.employeeName}</td>
                      <td className="px-6 py-4 text-slate-300">{emp.department}</td>
                      <td className="px-6 py-4 text-right">{balance.accrued}h</td>
                      <td className="px-6 py-4 text-right text-cyan-400">{balance.used}h</td>
                      <td className="px-6 py-4 text-right font-semibold text-emerald-400">
                        {balance.remaining}h
                      </td>
                      <td className="px-6 py-4 text-right">{usagePercent.toFixed(0)}%</td>
                      <td className="px-6 py-4">
                        <div className="w-full max-w-[120px] mx-auto bg-slate-800 rounded-full h-2">
                          <div
                            className={`h-2 rounded-full ${
                              usagePercent > 75 ? 'bg-red-500' :
                              usagePercent > 50 ? 'bg-yellow-500' :
                              'bg-blue-500'
                            }`}
                            style={{ width: `${usagePercent}%` }}
                          />
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>

        {/* Department Summary */}
        <div className="mt-6 bg-slate-900 rounded-lg p-6 border border-slate-800">
          <h2 className="text-xl font-semibold mb-4">Department Summary</h2>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            {Object.values(
              balances.reduce((acc, emp) => {
                const dept = emp.department;
                if (!acc[dept]) {
                  acc[dept] = { department: dept, remaining: 0, used: 0, employees: 0 };
                }
                const balance = emp.balances[selectedType];
                acc[dept].remaining += balance.remaining;
                acc[dept].used += balance.used;
                acc[dept].employees += 1;
                return acc;
              }, {} as Record<string, { department: string; remaining: number; used: number; employees: number }>)
            ).map(dept => (
              <div key={dept.department} className="p-4 bg-slate-800/50 rounded-lg">
                <div className="font-semibold mb-2">{dept.department}</div>
                <div className="grid grid-cols-3 gap-2 text-sm">
                  <div>
                    <div className="text-slate-400">Employees</div>
                    <div className="font-medium">{dept.employees}</div>
                  </div>
                  <div>
                    <div className="text-slate-400">Used</div>
                    <div className="font-medium text-cyan-400">{dept.used}h</div>
                  </div>
                  <div>
                    <div className="text-slate-400">Remaining</div>
                    <div className="font-medium text-emerald-400">{dept.remaining}h</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ title, value, icon }: {
  title: string;
  value: string;
  icon: React.ReactNode;
}) {
  return (
    <div className="bg-slate-900 rounded-lg p-6 border border-slate-800">
      <div className="flex items-start justify-between mb-4">
        <div className="text-slate-400 text-sm font-medium">{title}</div>
        {icon}
      </div>
      <div className="text-3xl font-bold">{value}</div>
    </div>
  );
}
