import React, { useState, useEffect } from 'react';
import { Calendar as CalendarIcon, ChevronLeft, ChevronRight, DollarSign } from 'lucide-react';

interface PayScheduleEvent {
  date: string;
  type: 'payday' | 'deadline' | 'period-start' | 'period-end';
  amount?: number;
  employees?: number;
  status?: string;
}

export default function PayrollCalendar() {
  const [currentDate, setCurrentDate] = useState(new Date(2024, 1)); // February 2024
  const [events, setEvents] = useState<Record<string, PayScheduleEvent[]>>({});

  useEffect(() => {
    // Mock data - in production, fetch from Gusto MCP
    setEvents({
      '2024-02-01': [{ type: 'period-start', date: '2024-02-01' }],
      '2024-02-02': [{ type: 'payday', date: '2024-02-02', amount: 387500, employees: 124, status: 'processed' }],
      '2024-02-15': [
        { type: 'period-end', date: '2024-02-15' },
        { type: 'deadline', date: '2024-02-15' }
      ],
      '2024-02-16': [{ type: 'payday', date: '2024-02-16', amount: 425000, employees: 124, status: 'pending' }],
      '2024-02-29': [{ type: 'period-end', date: '2024-02-29' }]
    });
  }, []);

  const daysInMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();
  const firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDay();

  const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

  const previousMonth = () => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() - 1));
  };

  const nextMonth = () => {
    setCurrentDate(new Date(currentDate.getFullYear(), currentDate.getMonth() + 1));
  };

  const getDateKey = (day: number) => {
    const year = currentDate.getFullYear();
    const month = String(currentDate.getMonth() + 1).padStart(2, '0');
    const dayStr = String(day).padStart(2, '0');
    return `${year}-${month}-${dayStr}`;
  };

  const renderCalendarDays = () => {
    const days = [];
    
    // Empty cells for days before month starts
    for (let i = 0; i < firstDayOfMonth; i++) {
      days.push(<div key={`empty-${i}`} className="h-32 bg-slate-900/30" />);
    }

    // Days of the month
    for (let day = 1; day <= daysInMonth; day++) {
      const dateKey = getDateKey(day);
      const dayEvents = events[dateKey] || [];
      
      days.push(
        <div
          key={day}
          className="h-32 bg-slate-900 border border-slate-800 p-2 hover:bg-slate-800/50 transition-colors"
        >
          <div className="font-medium mb-2">{day}</div>
          <div className="space-y-1">
            {dayEvents.map((event, idx) => (
              <EventBadge key={idx} event={event} />
            ))}
          </div>
        </div>
      );
    }

    return days;
  };

  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">
            <CalendarIcon className="text-purple-400" size={36} />
            Payroll Calendar
          </h1>
          <p className="text-slate-400">View payroll schedule and important dates</p>
        </div>

        {/* Calendar Controls */}
        <div className="bg-slate-900 rounded-lg p-6 mb-6 border border-slate-800">
          <div className="flex items-center justify-between">
            <button
              onClick={previousMonth}
              className="p-2 hover:bg-slate-800 rounded-lg transition-colors"
            >
              <ChevronLeft size={24} />
            </button>
            <h2 className="text-2xl font-bold">
              {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
            </h2>
            <button
              onClick={nextMonth}
              className="p-2 hover:bg-slate-800 rounded-lg transition-colors"
            >
              <ChevronRight size={24} />
            </button>
          </div>
        </div>

        {/* Legend */}
        <div className="bg-slate-900 rounded-lg p-6 mb-6 border border-slate-800">
          <div className="flex flex-wrap gap-4">
            <LegendItem color="bg-emerald-500" label="Payday" />
            <LegendItem color="bg-yellow-500" label="Payroll Deadline" />
            <LegendItem color="bg-blue-500" label="Period Start" />
            <LegendItem color="bg-purple-500" label="Period End" />
          </div>
        </div>

        {/* Calendar Grid */}
        <div className="bg-slate-900 rounded-lg border border-slate-800 overflow-hidden">
          {/* Day Headers */}
          <div className="grid grid-cols-7 bg-slate-800/50">
            {['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map(day => (
              <div key={day} className="p-4 text-center font-semibold border border-slate-800">
                {day}
              </div>
            ))}
          </div>

          {/* Calendar Days */}
          <div className="grid grid-cols-7">
            {renderCalendarDays()}
          </div>
        </div>

        {/* Upcoming Events */}
        <div className="mt-6 bg-slate-900 rounded-lg p-6 border border-slate-800">
          <h2 className="text-xl font-semibold mb-4">Upcoming Payroll Events</h2>
          <div className="space-y-3">
            <UpcomingEvent
              date="Feb 15, 2024"
              title="Payroll Deadline"
              description="Submit payroll by 12:00 PM"
              type="deadline"
            />
            <UpcomingEvent
              date="Feb 16, 2024"
              title="Payday"
              description="124 employees • $425,000"
              type="payday"
            />
            <UpcomingEvent
              date="Feb 29, 2024"
              title="Pay Period End"
              description="February 2024 period closes"
              type="period-end"
            />
          </div>
        </div>
      </div>
    </div>
  );
}

function EventBadge({ event }: { event: PayScheduleEvent }) {
  const configs = {
    payday: { bg: 'bg-emerald-500/20', border: 'border-emerald-500/50', text: 'text-emerald-400', label: '💰 Payday' },
    deadline: { bg: 'bg-yellow-500/20', border: 'border-yellow-500/50', text: 'text-yellow-400', label: '⏰ Deadline' },
    'period-start': { bg: 'bg-blue-500/20', border: 'border-blue-500/50', text: 'text-blue-400', label: '▶️ Start' },
    'period-end': { bg: 'bg-purple-500/20', border: 'border-purple-500/50', text: 'text-purple-400', label: '⏹️ End' }
  };

  const config = configs[event.type];

  return (
    <div className={`text-xs px-2 py-1 rounded border ${config.bg} ${config.border} ${config.text}`}>
      {config.label}
      {event.amount && <div className="font-semibold">${(event.amount / 1000).toFixed(0)}k</div>}
    </div>
  );
}

function LegendItem({ color, label }: { color: string; label: string }) {
  return (
    <div className="flex items-center gap-2">
      <div className={`w-4 h-4 rounded ${color}`} />
      <span className="text-sm text-slate-300">{label}</span>
    </div>
  );
}

function UpcomingEvent({ date, title, description, type }: {
  date: string;
  title: string;
  description: string;
  type: string;
}) {
  const icons = {
    payday: '💰',
    deadline: '⏰',
    'period-end': '⏹️'
  };

  return (
    <div className="flex items-start gap-4 p-4 bg-slate-800/50 rounded-lg hover:bg-slate-800 transition-colors">
      <div className="text-2xl">{icons[type as keyof typeof icons]}</div>
      <div className="flex-1">
        <div className="font-semibold">{title}</div>
        <div className="text-sm text-slate-400">{description}</div>
      </div>
      <div className="text-sm text-slate-400">{date}</div>
    </div>
  );
}
