import React, { useState, useEffect } from 'react';
import { AlertTriangle, DollarSign, User, FileText, Calendar } from 'lucide-react';

interface Garnishment {
  id: string;
  employee: { name: string; id: string };
  garnishmentType: 'child-support' | 'tax-levy' | 'student-loan' | 'other';
  amount: number;
  frequency: 'per-paycheck' | 'monthly';
  startDate: string;
  endDate?: string;
  status: 'active' | 'completed' | 'pending';
  totalWithheld: number;
  caseNumber?: string;
  agency: string;
}

export default function GarnishmentManager() {
  const [garnishments, setGarnishments] = useState<Garnishment[]>([]);
  const [filter, setFilter] = useState<string>('all');

  useEffect(() => {
    // Mock data - in production, fetch from Gusto MCP
    setGarnishments([
      {
        id: '1',
        employee: { name: 'John Smith', id: 'emp_001' },
        garnishmentType: 'child-support',
        amount: 500,
        frequency: 'per-paycheck',
        startDate: '2023-06-01',
        status: 'active',
        totalWithheld: 12000,
        caseNumber: 'CS-2023-4567',
        agency: 'State Child Support Agency'
      },
      {
        id: '2',
        employee: { name: 'Maria Garcia', id: 'emp_002' },
        garnishmentType: 'student-loan',
        amount: 300,
        frequency: 'per-paycheck',
        startDate: '2023-09-15',
        status: 'active',
        totalWithheld: 7200,
        caseNumber: 'SL-987654',
        agency: 'Department of Education'
      },
      {
        id: '3',
        employee: { name: 'Robert Taylor', id: 'emp_003' },
        garnishmentType: 'tax-levy',
        amount: 750,
        frequency: 'per-paycheck',
        startDate: '2024-01-01',
        endDate: '2024-06-30',
        status: 'active',
        totalWithheld: 3000,
        caseNumber: 'IRS-2024-123',
        agency: 'Internal Revenue Service'
      },
      {
        id: '4',
        employee: { name: 'Sarah Williams', id: 'emp_004' },
        garnishmentType: 'child-support',
        amount: 425,
        frequency: 'per-paycheck',
        startDate: '2022-03-01',
        endDate: '2023-12-31',
        status: 'completed',
        totalWithheld: 19125,
        caseNumber: 'CS-2022-8901',
        agency: 'State Child Support Agency'
      }
    ]);
  }, []);

  const filteredGarnishments = filter === 'all'
    ? garnishments
    : garnishments.filter(g => g.status === filter);

  const stats = {
    active: garnishments.filter(g => g.status === 'active').length,
    totalWithheld: garnishments.reduce((sum, g) => sum + g.totalWithheld, 0),
    monthlyTotal: garnishments
      .filter(g => g.status === 'active')
      .reduce((sum, g) => sum + (g.frequency === 'per-paycheck' ? g.amount * 2 : g.amount), 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">
            <AlertTriangle className="text-orange-400" size={36} />
            Garnishment Manager
          </h1>
          <p className="text-slate-400">Track and manage employee wage garnishments</p>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
          <StatCard
            title="Active Garnishments"
            value={stats.active}
            icon={<AlertTriangle className="text-orange-400" />}
          />
          <StatCard
            title="Total Withheld YTD"
            value={`$${stats.totalWithheld.toLocaleString()}`}
            icon={<DollarSign className="text-red-400" />}
          />
          <StatCard
            title="Monthly Total"
            value={`$${stats.monthlyTotal.toLocaleString()}`}
            icon={<Calendar className="text-blue-400" />}
          />
        </div>

        {/* Filters */}
        <div className="bg-slate-900 rounded-lg p-6 mb-6 border border-slate-800">
          <div className="flex gap-2">
            {['all', 'active', 'pending', 'completed'].map(status => (
              <button
                key={status}
                onClick={() => setFilter(status)}
                className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                  filter === status
                    ? 'bg-blue-600 text-white'
                    : 'bg-slate-800 text-slate-300 hover:bg-slate-700'
                }`}
              >
                {status.charAt(0).toUpperCase() + status.slice(1)}
              </button>
            ))}
          </div>
          <div className="mt-4 text-slate-400">
            Showing {filteredGarnishments.length} garnishment{filteredGarnishments.length !== 1 ? 's' : ''}
          </div>
        </div>

        {/* Garnishments List */}
        <div className="space-y-4">
          {filteredGarnishments.map(garnishment => (
            <GarnishmentCard key={garnishment.id} garnishment={garnishment} />
          ))}
        </div>
      </div>
    </div>
  );
}

function StatCard({ title, value, icon }: {
  title: string;
  value: string | number;
  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>
  );
}

function GarnishmentCard({ garnishment }: { garnishment: Garnishment }) {
  const statusConfig = {
    active: {
      bg: 'bg-orange-500/10',
      border: 'border-orange-500/30',
      text: 'text-orange-400'
    },
    pending: {
      bg: 'bg-yellow-500/10',
      border: 'border-yellow-500/30',
      text: 'text-yellow-400'
    },
    completed: {
      bg: 'bg-green-500/10',
      border: 'border-green-500/30',
      text: 'text-green-400'
    }
  };

  const typeLabels = {
    'child-support': { label: 'Child Support', emoji: '👶', color: 'text-blue-400' },
    'tax-levy': { label: 'Tax Levy', emoji: '📋', color: 'text-red-400' },
    'student-loan': { label: 'Student Loan', emoji: '🎓', color: 'text-purple-400' },
    'other': { label: 'Other', emoji: '📄', color: 'text-slate-400' }
  };

  const config = statusConfig[garnishment.status];
  const typeInfo = typeLabels[garnishment.garnishmentType];

  return (
    <div className="bg-slate-900 rounded-lg p-6 border border-slate-800 hover:border-orange-500/50 transition-colors">
      <div className="flex items-start justify-between mb-4">
        <div className="flex-1">
          <div className="flex items-center gap-3 mb-2">
            <User size={20} className="text-slate-400" />
            <h3 className="text-xl font-semibold">{garnishment.employee.name}</h3>
            <span className={`px-3 py-1 rounded-full text-sm font-medium border ${config.bg} ${config.border} ${config.text}`}>
              {garnishment.status.toUpperCase()}
            </span>
          </div>

          <div className={`flex items-center gap-2 ${typeInfo.color} mb-4`}>
            <span className="text-xl">{typeInfo.emoji}</span>
            <span className="font-medium">{typeInfo.label}</span>
          </div>

          <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
            <div>
              <div className="text-slate-400 text-sm mb-1">Amount Per {garnishment.frequency === 'per-paycheck' ? 'Paycheck' : 'Month'}</div>
              <div className="text-xl font-bold text-red-400">
                ${garnishment.amount.toLocaleString()}
              </div>
            </div>

            <div>
              <div className="text-slate-400 text-sm mb-1">Total Withheld</div>
              <div className="text-xl font-semibold">
                ${garnishment.totalWithheld.toLocaleString()}
              </div>
            </div>

            <div>
              <div className="text-slate-400 text-sm mb-1">Start Date</div>
              <div className="font-medium">{garnishment.startDate}</div>
              {garnishment.endDate && (
                <div className="text-sm text-slate-500">End: {garnishment.endDate}</div>
              )}
            </div>

            <div>
              <div className="text-slate-400 text-sm mb-1">Case Number</div>
              <div className="font-medium">{garnishment.caseNumber || 'N/A'}</div>
            </div>
          </div>

          <div className="mt-4 p-4 bg-slate-800/50 rounded-lg">
            <div className="text-slate-400 text-sm mb-1">Agency</div>
            <div className="font-medium">{garnishment.agency}</div>
          </div>
        </div>
      </div>
    </div>
  );
}
