import React, { useState, useEffect } from 'react';
import { DollarSign, Calendar, CheckCircle, Clock, AlertCircle, TrendingUp } from 'lucide-react';

interface PayRun {
  id: string;
  payrollDeadline: string;
  checkDate: string;
  payPeriod: { startDate: string; endDate: string };
  status: 'processed' | 'approved' | 'pending' | 'failed';
  totals: {
    companyDebit: number;
    employeeTaxes: number;
    employerTaxes: number;
    netPay: number;
  };
  employeeCount: number;
}

export default function PayrollDashboard() {
  const [payRuns, setPayRuns] = useState<PayRun[]>([]);
  const [stats, setStats] = useState({
    totalThisYear: 4250000,
    avgPerPayroll: 387500,
    upcomingPayrolls: 2,
    lastProcessed: '2024-02-01'
  });

  useEffect(() => {
    // Mock data - in production, fetch from Gusto MCP
    setPayRuns([
      {
        id: '1',
        payrollDeadline: '2024-02-15T12:00:00',
        checkDate: '2024-02-16',
        payPeriod: { startDate: '2024-02-01', endDate: '2024-02-15' },
        status: 'pending',
        totals: {
          companyDebit: 425000,
          employeeTaxes: 85000,
          employerTaxes: 42000,
          netPay: 298000
        },
        employeeCount: 124
      },
      {
        id: '2',
        payrollDeadline: '2024-02-01T12:00:00',
        checkDate: '2024-02-02',
        payPeriod: { startDate: '2024-01-16', endDate: '2024-01-31' },
        status: 'processed',
        totals: {
          companyDebit: 387500,
          employeeTaxes: 77500,
          employerTaxes: 38750,
          netPay: 271250
        },
        employeeCount: 124
      },
      {
        id: '3',
        payrollDeadline: '2024-01-15T12:00:00',
        checkDate: '2024-01-16',
        payPeriod: { startDate: '2024-01-01', endDate: '2024-01-15' },
        status: 'processed',
        totals: {
          companyDebit: 387500,
          employeeTaxes: 77500,
          employerTaxes: 38750,
          netPay: 271250
        },
        employeeCount: 124
      },
      {
        id: '4',
        payrollDeadline: '2024-03-01T12:00:00',
        checkDate: '2024-03-02',
        payPeriod: { startDate: '2024-02-16', endDate: '2024-02-29' },
        status: 'approved',
        totals: {
          companyDebit: 387500,
          employeeTaxes: 77500,
          employerTaxes: 38750,
          netPay: 271250
        },
        employeeCount: 124
      }
    ]);
  }, []);

  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} />
            Payroll Dashboard
          </h1>
          <p className="text-slate-400">Manage and track all payroll runs</p>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <StatCard
            title="Total YTD"
            value={`$${(stats.totalThisYear / 1000000).toFixed(2)}M`}
            icon={<TrendingUp className="text-emerald-400" />}
            trend="+12% vs last year"
          />
          <StatCard
            title="Avg Per Payroll"
            value={`$${(stats.avgPerPayroll / 1000).toFixed(0)}k`}
            icon={<DollarSign className="text-blue-400" />}
            trend="Last 12 payrolls"
          />
          <StatCard
            title="Upcoming"
            value={stats.upcomingPayrolls}
            icon={<Calendar className="text-purple-400" />}
            trend="Next 30 days"
          />
          <StatCard
            title="Last Processed"
            value={stats.lastProcessed}
            icon={<CheckCircle className="text-green-400" />}
            trend="124 employees"
          />
        </div>

        {/* Payroll Runs List */}
        <div className="bg-slate-900 rounded-lg border border-slate-800">
          <div className="p-6 border-b border-slate-800">
            <h2 className="text-xl font-semibold flex items-center justify-between">
              Recent Payroll Runs
              <button className="px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-lg text-sm font-medium transition-colors">
                + New Payroll
              </button>
            </h2>
          </div>

          <div className="divide-y divide-slate-800">
            {payRuns.map(payRun => (
              <PayrollRunCard key={payRun.id} payRun={payRun} />
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

function StatCard({ title, value, icon, trend }: {
  title: string;
  value: string | number;
  icon: React.ReactNode;
  trend: string;
}) {
  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 mb-2">{value}</div>
      <div className="text-sm text-slate-500">{trend}</div>
    </div>
  );
}

function PayrollRunCard({ payRun }: { payRun: PayRun }) {
  const statusConfig = {
    processed: {
      icon: <CheckCircle size={20} className="text-green-400" />,
      bg: 'bg-green-500/10',
      border: 'border-green-500/20',
      text: 'text-green-400'
    },
    approved: {
      icon: <CheckCircle size={20} className="text-blue-400" />,
      bg: 'bg-blue-500/10',
      border: 'border-blue-500/20',
      text: 'text-blue-400'
    },
    pending: {
      icon: <Clock size={20} className="text-yellow-400" />,
      bg: 'bg-yellow-500/10',
      border: 'border-yellow-500/20',
      text: 'text-yellow-400'
    },
    failed: {
      icon: <AlertCircle size={20} className="text-red-400" />,
      bg: 'bg-red-500/10',
      border: 'border-red-500/20',
      text: 'text-red-400'
    }
  };

  const config = statusConfig[payRun.status];

  return (
    <div className="p-6 hover:bg-slate-800/50 transition-colors cursor-pointer">
      <div className="flex items-start justify-between">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-3">
            <h3 className="text-lg font-semibold">
              Pay Period: {payRun.payPeriod.startDate} - {payRun.payPeriod.endDate}
            </h3>
            <span className={`px-3 py-1 rounded-full text-sm font-medium border ${config.bg} ${config.border} ${config.text} flex items-center gap-1`}>
              {config.icon}
              {payRun.status.toUpperCase()}
            </span>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 text-sm">
            <div>
              <div className="text-slate-400 mb-1">Check Date</div>
              <div className="font-medium">{payRun.checkDate}</div>
            </div>
            <div>
              <div className="text-slate-400 mb-1">Employees</div>
              <div className="font-medium">{payRun.employeeCount}</div>
            </div>
            <div>
              <div className="text-slate-400 mb-1">Net Pay</div>
              <div className="font-medium text-emerald-400">
                ${(payRun.totals.netPay / 1000).toFixed(0)}k
              </div>
            </div>
            <div>
              <div className="text-slate-400 mb-1">Employee Taxes</div>
              <div className="font-medium">
                ${(payRun.totals.employeeTaxes / 1000).toFixed(0)}k
              </div>
            </div>
            <div>
              <div className="text-slate-400 mb-1">Company Debit</div>
              <div className="font-medium text-blue-400">
                ${(payRun.totals.companyDebit / 1000).toFixed(0)}k
              </div>
            </div>
          </div>
        </div>

        <button className="ml-4 px-4 py-2 bg-slate-800 hover:bg-slate-700 rounded-lg text-sm font-medium transition-colors">
          View Details
        </button>
      </div>
    </div>
  );
}
