import React, { useState } from 'react';
import { Room, Property, Transaction, User } from '../types';
import { Calendar as CalendarIcon, ChevronLeft, ChevronRight, Info, User as UserIcon, Clock, Building, BedDouble, HelpCircle } from 'lucide-react';

interface OccupancyCalendarProps {
  rooms: Room[];
  properties: Property[];
  transactions: Transaction[];
  currentUser: User;
}

export default function OccupancyCalendar({ rooms, properties, transactions, currentUser }: OccupancyCalendarProps) {
  const [selectedPropertyId, setSelectedPropertyId] = useState<string>(properties[0]?.id || '');
  const [selectedRoomId, setSelectedRoomId] = useState<string>('');
  
  // Date states - default to current local time (June 2026)
  const [currentYear, setCurrentYear] = useState(2026);
  const [currentMonth, setCurrentMonth] = useState(5); // 0-indexed (5 = June)

  const monthNames = [
    'Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni',
    'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'
  ];

  // Filter properties by owner role
  let myProperties = properties;
  if (currentUser.role === 'admin') {
    myProperties = properties.filter((p) => p.id === currentUser.propertyId);
  } else if (currentUser.role === 'owner') {
    myProperties = properties.filter((p) => p.ownerId === currentUser.id);
  }

  // Handle cascading rooms list
  const propertyRooms = rooms.filter(r => r.propertyId === selectedPropertyId);
  
  // Set default room if none selected
  React.useEffect(() => {
    if (propertyRooms.length > 0 && !selectedRoomId) {
      setSelectedRoomId(propertyRooms[0].id);
    }
  }, [selectedPropertyId, propertyRooms]);

  // Navigate Months
  const handlePrevMonth = () => {
    if (currentMonth === 0) {
      setCurrentMonth(11);
      setCurrentYear(prev => prev - 1);
    } else {
      setCurrentMonth(prev => prev - 1);
    }
  };

  const handleNextMonth = () => {
    if (currentMonth === 11) {
      setCurrentMonth(0);
      setCurrentYear(prev => prev + 1);
    } else {
      setCurrentMonth(prev => prev + 1);
    }
  };

  // Extract all bookings/stay reservations for the selected Room
  const activeRoom = rooms.find(r => r.id === selectedRoomId);
  const activeProperty = properties.find(p => p.id === selectedPropertyId);

  // Fetch transactions for this room or property
  const roomTransactions = transactions.filter(t => {
    const matchesProperty = t.propertyId === selectedPropertyId;
    const matchesRoom = selectedRoomId ? t.roomId === selectedRoomId : true;
    return matchesProperty && matchesRoom && t.status === 'paid' && (t.type === 'stay' || t.type === 'rent');
  });

  // Check if a specific date (YYYY-MM-DD) is occupied and get detail
  const getBookingForDate = (dateString: string) => {
    // 1. Check transactions first (which are authoritative)
    for (const tx of roomTransactions) {
      if (tx.startDate && tx.endDate) {
        const d = new Date(dateString);
        const start = new Date(tx.startDate);
        const end = new Date(tx.endDate);
        
        // Zero out times
        d.setHours(0,0,0,0);
        start.setHours(0,0,0,0);
        end.setHours(0,0,0,0);

        if (d >= start && d <= end) {
          return {
            buyerName: tx.buyerName,
            txId: tx.id,
            type: tx.type,
            startDate: tx.startDate,
            endDate: tx.endDate,
            totalPrice: tx.totalPrice
          };
        }
      }
    }

    // 2. Fallback to room's bookedDates (e.g. ["2026-07-01 s/d 2026-07-05"])
    if (activeRoom && activeRoom.bookedDates) {
      for (const bStr of activeRoom.bookedDates) {
        if (bStr.includes(' s/d ')) {
          const [sPart, ePart] = bStr.split(' s/d ');
          const d = new Date(dateString);
          const start = new Date(sPart);
          const end = new Date(ePart);
          
          d.setHours(0,0,0,0);
          start.setHours(0,0,0,0);
          end.setHours(0,0,0,0);

          if (d >= start && d <= end) {
            return {
              buyerName: 'Pemesanan Offline / PMS',
              txId: 'offline',
              type: 'stay',
              startDate: sPart,
              endDate: ePart,
              totalPrice: 0
            };
          }
        }
      }
    }

    return null;
  };

  // Generate Calendar Days Grid
  const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();
  const firstDayIndex = new Date(currentYear, currentMonth, 1).getDay(); // 0 is Sunday

  const calendarCells = [];
  
  // Fill previous month trailing days
  const prevMonthDays = new Date(currentYear, currentMonth, 0).getDate();
  for (let i = firstDayIndex - 1; i >= 0; i--) {
    calendarCells.push({
      day: prevMonthDays - i,
      isCurrentMonth: false,
      dateString: ''
    });
  }

  // Fill current month days
  for (let day = 1; day <= daysInMonth; day++) {
    const mm = String(currentMonth + 1).padStart(2, '0');
    const dd = String(day).padStart(2, '0');
    const dateString = `${currentYear}-${mm}-${dd}`;
    calendarCells.push({
      day,
      isCurrentMonth: true,
      dateString
    });
  }

  // Fill next month trailing days
  const remainingCells = 42 - calendarCells.length;
  for (let i = 1; i <= remainingCells; i++) {
    calendarCells.push({
      day: i,
      isCurrentMonth: false,
      dateString: ''
    });
  }

  const formatRupiah = (num: number) => {
    return new Intl.NumberFormat('id-ID', {
      style: 'currency',
      currency: 'IDR',
      maximumFractionDigits: 0
    }).format(num);
  };

  return (
    <div className="space-y-6">
      <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs">
        <h3 className="font-sans font-bold text-base text-gray-900 flex items-center space-x-1.5">
          <CalendarIcon className="h-5 w-5 text-blue-600" />
          <span>Kalender Okupansi Kamar & Gedung</span>
        </h3>
        <p className="text-xs text-gray-400 mt-0.5">Pantau jadwal pengisian harian kamar hotel, sewa villa, apartemen, atau ruang gedung Anda secara interaktif.</p>

        {/* Cascading selection panel */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4 pt-4 border-t border-gray-50">
          <div className="space-y-1.5">
            <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider">Pilih Properti / Gedung</label>
            <div className="relative">
              <select
                value={selectedPropertyId}
                onChange={(e) => { setSelectedPropertyId(e.target.value); setSelectedRoomId(''); }}
                className="w-full pl-8 pr-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
              >
                {myProperties.map(p => (
                  <option key={p.id} value={p.id}>{p.name} ({p.type})</option>
                ))}
              </select>
              <Building className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-gray-400" />
            </div>
          </div>

          <div className="space-y-1.5">
            <label className="block text-xs font-bold text-gray-400 uppercase tracking-wider">Pilih Unit Kamar / Ruangan</label>
            <div className="relative">
              <select
                value={selectedRoomId}
                onChange={(e) => setSelectedRoomId(e.target.value)}
                className="w-full pl-8 pr-3 py-2 border border-gray-200 rounded-lg text-xs bg-white focus:outline-hidden focus:border-blue-500"
                disabled={propertyRooms.length === 0}
              >
                {propertyRooms.length === 0 ? (
                  <option value="">Tidak ada kamar terdaftar</option>
                ) : (
                  propertyRooms.map(r => (
                    <option key={r.id} value={r.id}>Unit {r.roomNumber} - {r.type}</option>
                  ))
                )}
              </select>
              <BedDouble className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-gray-400" />
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left/Middle (2/3 width): Visual Calendar Grid */}
        <div className="lg:col-span-2 bg-white p-6 rounded-xl border border-gray-100 shadow-xs space-y-4">
          {/* Calendar Header with Navigation */}
          <div className="flex justify-between items-center pb-2 border-b border-gray-50">
            <div className="flex items-center space-x-2">
              <span className="font-sans font-black text-base text-gray-800 uppercase">
                {monthNames[currentMonth]} {currentYear}
              </span>
            </div>
            <div className="flex items-center space-x-1">
              <button
                onClick={handlePrevMonth}
                className="p-1.5 bg-gray-50 border border-gray-200 text-gray-600 rounded-lg hover:bg-gray-100 cursor-pointer"
              >
                <ChevronLeft className="h-4 w-4" />
              </button>
              <button
                onClick={handleNextMonth}
                className="p-1.5 bg-gray-50 border border-gray-200 text-gray-600 rounded-lg hover:bg-gray-100 cursor-pointer"
              >
                <ChevronRight className="h-4 w-4" />
              </button>
            </div>
          </div>

          {/* Weekday labels */}
          <div className="grid grid-cols-7 gap-2 text-center text-[10px] font-bold text-gray-400 uppercase tracking-wider pb-1">
            <span>Minggu</span>
            <span>Senin</span>
            <span>Selasa</span>
            <span>Rabu</span>
            <span>Kamis</span>
            <span>Jumat</span>
            <span>Sabtu</span>
          </div>

          {/* Days Grid */}
          <div className="grid grid-cols-7 gap-2.5">
            {calendarCells.map((cell, idx) => {
              if (!cell.isCurrentMonth) {
                return (
                  <div
                    key={idx}
                    className="h-16 rounded-xl bg-gray-50/50 border border-dashed border-gray-100 text-gray-300 text-xs p-1 font-semibold flex items-start justify-end"
                  >
                    <span>{cell.day}</span>
                  </div>
                );
              }

              const booking = getBookingForDate(cell.dateString);
              const isOccupied = booking !== null;

              return (
                <div
                  key={idx}
                  className={`h-16 rounded-xl border p-1 text-xs flex flex-col justify-between transition-all relative group ${
                    isOccupied
                      ? 'bg-rose-50 border-rose-200 text-rose-900 ring-2 ring-rose-500/5'
                      : 'bg-emerald-50/40 border-emerald-100 text-emerald-900 hover:bg-emerald-50'
                  }`}
                  title={isOccupied ? `Dipesan oleh: ${booking.buyerName}\nSewa: ${booking.startDate} s/d ${booking.endDate}` : 'Kosong & Tersedia'}
                >
                  {/* Day Number */}
                  <div className="flex justify-between items-center shrink-0">
                    <span className={`h-1.5 w-1.5 rounded-full ${isOccupied ? 'bg-rose-500' : 'bg-emerald-400'}`}></span>
                    <span className="font-bold text-[11px]">{cell.day}</span>
                  </div>

                  {/* Customer display badge if occupied */}
                  {isOccupied && (
                    <div className="text-[9px] bg-rose-500 text-white rounded-md px-1 py-0.5 truncate leading-tight font-extrabold w-full text-center">
                      {booking.buyerName}
                    </div>
                  )}

                  {/* Pricing indicator if vacant */}
                  {!isOccupied && activeRoom && (
                    <div className="text-[8px] text-emerald-700 text-right leading-none font-bold">
                      Tersedia
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* Color Key Guide */}
          <div className="flex items-center space-x-6 text-[10px] font-bold text-gray-500 pt-3 border-t border-gray-50">
            <div className="flex items-center space-x-1.5">
              <span className="h-3 w-3 bg-emerald-500 rounded-sm border border-emerald-600 block"></span>
              <span>Kamar Tersedia (Kosong)</span>
            </div>
            <div className="flex items-center space-x-1.5">
              <span className="h-3 w-3 bg-rose-500 rounded-sm border border-rose-600 block"></span>
              <span>Terisi / Booking Aktif</span>
            </div>
            <div className="flex items-center space-x-1.5">
              <span className="h-3 w-3 bg-gray-100 rounded-sm border border-dashed border-gray-300 block"></span>
              <span>Hari Di Luar Bulan Ini</span>
            </div>
          </div>
        </div>

        {/* Right (1/3 width): Bookings List Side-Details Panel */}
        <div className="bg-white p-5 rounded-xl border border-gray-100 shadow-xs flex flex-col justify-between space-y-4">
          <div className="space-y-4">
            <div>
              <h4 className="font-bold text-sm text-gray-900">Pemesanan Bulan Ini</h4>
              <p className="text-[10px] text-gray-400">Daftar reservasi masuk untuk unit yang terpilih saat ini.</p>
            </div>

            {/* List of bookings */}
            <div className="space-y-3 max-h-[300px] overflow-y-auto pr-1">
              {roomTransactions.length === 0 ? (
                <div className="py-12 text-center text-xs text-gray-400 italic">
                  Belum ada riwayat transaksi booking bulan ini.
                </div>
              ) : (
                roomTransactions.map((tx) => (
                  <div key={tx.id} className="p-3 bg-gray-50 rounded-xl border border-gray-100 space-y-2 text-xs">
                    <div className="flex justify-between items-center font-bold">
                      <span className="text-gray-900 flex items-center space-x-1">
                        <UserIcon className="h-3.5 w-3.5 text-blue-500 shrink-0" />
                        <span className="truncate max-w-[100px]">{tx.buyerName}</span>
                      </span>
                      <span className="text-[10px] bg-blue-100 text-blue-800 px-1.5 py-0.5 rounded-md uppercase">
                        {tx.type === 'stay' ? 'Stay Harian' : 'Sewa Bulanan'}
                      </span>
                    </div>

                    <div className="text-[11px] text-gray-500 flex items-center space-x-1">
                      <Clock className="h-3 w-3 text-gray-400 shrink-0" />
                      <span>{tx.startDate} s/d {tx.endDate}</span>
                    </div>

                    <div className="flex justify-between text-[11px] pt-1.5 border-t border-gray-100/50">
                      <span className="text-gray-400">Total Biaya:</span>
                      <span className="font-extrabold text-gray-900">{formatRupiah(tx.totalPrice)}</span>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

          {/* Quick instructions block */}
          <div className="bg-blue-50/40 p-3.5 rounded-xl border border-blue-100/30 text-[11px] text-slate-700 space-y-1">
            <p className="font-bold text-blue-800 flex items-center space-x-1">
              <Info className="h-3.5 w-3.5 text-blue-600 shrink-0" />
              <span>Info Penggunaan</span>
            </p>
            <p className="leading-relaxed">Sistem menyinkronkan transaksi bertipe <strong>Lunas/Paid</strong> dan rentang tanggal sewa untuk mewarnai kalender secara real-time. Jika Anda mengosongkan unit di Dashboard, maka status harian akan kembali tersedia.</p>
          </div>
        </div>
      </div>
    </div>
  );
}
