'use client';
import { useState } from 'react';
import { LeaveRequest, LEAVE_POLICIES, DEPARTMENTS, PUBLIC_HOLIDAYS } from './leaveData';

interface Props {
  requests: LeaveRequest[];
  highlightApproved?: boolean;
  singleUserView?: boolean;
}

const MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const DAYS_OF_WEEK = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

export default function LeaveCalendarTab({ requests, highlightApproved, singleUserView }: Props) {
  const [year, setYear] = useState(2026);
  const [month, setMonth] = useState(3);
  const [deptFilter, setDeptFilter] = useState('All Departments');
  const [hoveredDay, setHoveredDay] = useState<number | null>(null);

  const activeRequests = requests.filter(r => r.status === 'Approved' || r.status === 'HOS Approved' || r.status === 'HOD Approved');
  const filtered = deptFilter === 'All Departments' ? activeRequests : activeRequests.filter(r => r.dept === deptFilter);

  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const getDateStr = (day: number) => `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;

  const getLeavesForDay = (day: number) => {
    const ds = getDateStr(day);
    return filtered.filter(r => r.startDate <= ds && r.endDate >= ds);
  };

  const isHoliday = (day: number) => PUBLIC_HOLIDAYS.find(h => h.date === getDateStr(day));
  const isWeekend = (day: number) => [0, 6].includes(new Date(year, month, day).getDay());
  const isToday = (day: number) => {
    const t = new Date();
    return t.getDate() === day && t.getMonth() === month && t.getFullYear() === year;
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex items-center gap-2 bg-white border border-gray-200 rounded-xl px-3 py-2">
          <button onClick={() => { if (month === 0) { setMonth(11); setYear(y => y - 1); } else setMonth(m => m - 1); }}
            className="w-6 h-6 flex items-center justify-center rounded cursor-pointer hover:bg-gray-100">
            <i className="ri-arrow-left-s-line text-gray-600"></i>
          </button>
          <span className="text-sm font-semibold text-gray-700 w-36 text-center">{MONTHS[month]} {year}</span>
          <button onClick={() => { if (month === 11) { setMonth(0); setYear(y => y + 1); } else setMonth(m => m + 1); }}
            className="w-6 h-6 flex items-center justify-center rounded cursor-pointer hover:bg-gray-100">
            <i className="ri-arrow-right-s-line text-gray-600"></i>
          </button>
        </div>
        <select value={deptFilter} onChange={e => setDeptFilter(e.target.value)}
          className="border border-gray-200 rounded-xl px-3 py-2 text-sm outline-none cursor-pointer bg-white pr-8">
          {DEPARTMENTS.map(d => <option key={d}>{d}</option>)}
        </select>
        <div className="ml-auto flex items-center gap-3 flex-wrap">
          {LEAVE_POLICIES.slice(0, 5).map(p => (
            <div key={p.type} className="flex items-center gap-1.5">
              <div className="w-3 h-3 rounded-sm" style={{ background: p.color }}></div>
              <span className="text-xs text-gray-500">{p.label}</span>
            </div>
          ))}
        </div>
      </div>

      <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
        <div className="grid grid-cols-7 border-b border-gray-100">
          {DAYS_OF_WEEK.map(d => (
            <div key={d} className="py-3 text-center text-xs font-semibold text-gray-500 uppercase">{d}</div>
          ))}
        </div>
        <div className="grid grid-cols-7">
          {Array.from({ length: firstDay }, (_, i) => (
            <div key={`empty-${i}`} className="h-28 border-b border-r border-gray-50 bg-gray-50/30"></div>
          ))}
          {Array.from({ length: daysInMonth }, (_, i) => {
            const day = i + 1;
            const leaves = getLeavesForDay(day);
            const holiday = isHoliday(day);
            const weekend = isWeekend(day);
            const today = isToday(day);
            return (
              <div key={day}
                className={`h-28 border-b border-r border-gray-100 p-1.5 overflow-hidden transition-colors relative
                  ${weekend ? 'bg-gray-50/60' : 'bg-white hover:bg-gray-50/50'}`}
                onMouseEnter={() => setHoveredDay(day)}
                onMouseLeave={() => setHoveredDay(null)}>
                <div className={`w-6 h-6 flex items-center justify-center rounded-full text-xs font-semibold mb-1
                  ${today ? 'text-white' : weekend ? 'text-gray-400' : holiday ? 'text-red-500' : 'text-gray-700'}`}
                  style={today ? { background: '#b828a0' } : {}}>
                  {day}
                </div>
                {holiday && <p className="text-xs text-red-500 font-medium truncate leading-3 mb-0.5" style={{ fontSize: '10px' }}>{holiday.name}</p>}
                <div className="space-y-0.5">
                  {leaves.slice(0, 2).map((l, idx) => {
                    const policy = LEAVE_POLICIES.find(p => p.type === l.type);
                    const isHOSApproved = l.status === 'HOS Approved' || l.status === 'Approved';
                    const bgColor = isHOSApproved ? '#16a34a' : (policy?.color || '#b828a0');
                    return (
                      <div key={idx} className="text-xs px-1.5 py-0.5 rounded text-white truncate"
                        style={{ background: bgColor, fontSize: '10px' }}>
                        {singleUserView ? (policy?.label?.slice(0,4) || 'Leave') : l.employee.split(' ')[0]}
                        {isHOSApproved && <span style={{fontSize:'8px'}}> ✓</span>}
                      </div>
                    );
                  })}
                  {leaves.length > 2 && (
                    <p className="text-gray-400" style={{ fontSize: '10px' }}>+{leaves.length - 2} more</p>
                  )}
                </div>
                {hoveredDay === day && leaves.length > 0 && (
                  <div className="absolute z-20 left-0 top-full mt-1 bg-white border border-gray-200 rounded-xl shadow-xl p-3 min-w-[200px]">
                    <p className="text-xs font-semibold text-gray-600 mb-2">{MONTHS[month]} {day} — {leaves.length} on leave</p>
                    {leaves.map((l, idx) => {
                      const policy = LEAVE_POLICIES.find(p => p.type === l.type);
                      return (
                        <div key={idx} className="flex items-center gap-2 mb-1.5">
                          <div className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: policy?.color }}></div>
                          <div>
                            <p className="text-xs font-medium text-gray-700">{l.employee}</p>
                            <p className="text-xs text-gray-400">{l.dept} · {policy?.label}</p>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      </div>

      <div className="bg-white rounded-xl border border-gray-100 shadow-sm p-4">
        <h4 className="text-sm font-semibold text-gray-700 mb-3">Public Holidays — {year}</h4>
        <div className="grid grid-cols-5 gap-2">
          {PUBLIC_HOLIDAYS.map(h => (
            <div key={h.date} className="bg-red-50 rounded-lg px-3 py-2">
              <p className="text-xs font-semibold text-red-700">{h.name}</p>
              <p className="text-xs text-red-400">{h.date}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
