'use client'

import { useState } from 'react'
import { useAppStore } from '@/store'
import { showToast } from '@/components/ui/Toast'

const MONTHS = ['Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember']
const DAYS   = ['Min','Sen','Sel','Rab','Kam','Jum','Sab']

export function CalendarView() {
  const { projects, tasks } = useAppStore()
  const [date, setDate] = useState(new Date())

  const year  = date.getFullYear()
  const month = date.getMonth()

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

  // Map deadline day → project
  const deadlineMap: Record<number, typeof projects[0][]> = {}
  projects.forEach(p => {
    const d = new Date(p.deadline)
    if (d.getFullYear() === year && d.getMonth() === month) {
      const day = d.getDate()
      if (!deadlineMap[day]) deadlineMap[day] = []
      deadlineMap[day].push(p)
    }
  })

  // Map due day → tasks
  const taskMap: Record<number, typeof tasks[0][]> = {}
  tasks.forEach(t => {
    const d = new Date(t.dueDate)
    if (d.getFullYear() === year && d.getMonth() === month) {
      const day = d.getDate()
      if (!taskMap[day]) taskMap[day] = []
      taskMap[day].push(t)
    }
  })

  const prev = () => setDate(new Date(year, month - 1, 1))
  const next = () => setDate(new Date(year, month + 1, 1))

  const cells: (number | null)[] = [
    ...Array(firstDay).fill(null),
    ...Array.from({ length: daysInMonth }, (_, i) => i + 1),
  ]

  return (
    <div className="space-y-6 animate-fade-in">
      <div>
        <h1 className="text-xl font-bold text-gray-900">Kalender 📅</h1>
        <p className="text-sm text-gray-400 mt-0.5">Deadline proyek dan tugas bulan ini</p>
      </div>

      {/* Legend */}
      <div className="flex items-center gap-4 text-[11px]">
        <div className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-gold-500 inline-block" />Deadline Proyek</div>
        <div className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-indigo-400 inline-block" />Due Date Tugas</div>
        <div className="flex items-center gap-1.5"><span className="w-3 h-3 rounded-sm bg-gold-100 border border-gold-500 inline-block" />Hari Ini</div>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-150 p-5">
        {/* Nav */}
        <div className="flex items-center justify-between mb-5">
          <h2 className="text-base font-semibold text-gray-900">{MONTHS[month]} {year}</h2>
          <div className="flex gap-2">
            <button onClick={prev} className="px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-100 transition-all">◀ Prev</button>
            <button onClick={() => setDate(new Date())} className="px-3 py-1.5 text-xs border border-gold-500 rounded-lg hover:bg-gold-100 transition-all text-gold-700 font-medium" style={{ borderColor:'#F5C542', color:'#D4A017' }}>Hari Ini</button>
            <button onClick={next} className="px-3 py-1.5 text-xs border border-gray-200 rounded-lg hover:bg-gray-100 transition-all">Next ▶</button>
          </div>
        </div>

        {/* Day headers */}
        <div className="grid grid-cols-7 gap-1 mb-1">
          {DAYS.map(d => (
            <div key={d} className="text-center text-[10px] font-semibold text-gray-400 py-1">{d}</div>
          ))}
        </div>

        {/* Grid */}
        <div className="grid grid-cols-7 gap-1">
          {cells.map((day, i) => {
            if (!day) return <div key={`empty-${i}`} />

            const isToday = day === today.getDate() && month === today.getMonth() && year === today.getFullYear()
            const projs = deadlineMap[day] || []
            const ts    = taskMap[day] || []

            return (
              <div
                key={day}
                className={`min-h-[68px] rounded-lg p-1.5 border transition-all cursor-pointer hover:border-gold-400 ${
                  isToday ? 'bg-gold-50 border-gold-400' : 'bg-white border-gray-150'
                }`}
                style={isToday ? { background:'#FFF8DC', borderColor:'#F5C542' } : {}}
                onClick={() => {
                  const info = [...projs.map(p => `📁 ${p.title}`), ...ts.map(t => `✅ ${t.title}`)]
                  if (info.length) showToast(info.slice(0,2).join(' | '))
                  else showToast(`📅 ${day} ${MONTHS[month]} ${year}`)
                }}
              >
                <div className={`text-xs font-semibold mb-1 ${isToday ? 'text-gold-700' : 'text-gray-700'}`}
                  style={isToday ? { color:'#D4A017' } : {}}
                >
                  {day}
                </div>
                {projs.slice(0,1).map(p => (
                  <div
                    key={p.id}
                    className="text-[9px] font-semibold text-white rounded px-1 py-0.5 mb-0.5 truncate"
                    style={{ background: p.color }}
                    title={p.title}
                  >
                    {p.title}
                  </div>
                ))}
                {ts.length > 0 && (
                  <div className="text-[9px] font-semibold text-white rounded px-1 py-0.5 truncate bg-indigo-400" title={ts[0].title}>
                    {ts[0].title}
                  </div>
                )}
                {(projs.length + ts.length) > 2 && (
                  <div className="text-[9px] text-gray-400">+{projs.length + ts.length - 2}</div>
                )}
              </div>
            )
          })}
        </div>
      </div>

      {/* Upcoming deadlines */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-150 overflow-hidden">
        <div className="px-5 py-4 border-b border-gray-100">
          <h3 className="text-sm font-semibold text-gray-800">Deadline Mendatang</h3>
        </div>
        <div className="divide-y divide-gray-50">
          {projects
            .filter(p => new Date(p.deadline) >= new Date())
            .sort((a, b) => new Date(a.deadline).getTime() - new Date(b.deadline).getTime())
            .slice(0, 5)
            .map(p => {
              const diff = Math.ceil((new Date(p.deadline).getTime() - Date.now()) / 86_400_000)
              return (
                <div key={p.id} className="px-5 py-3 flex items-center gap-3 hover:bg-gray-50 transition-colors">
                  <div className="w-3 h-3 rounded-full flex-shrink-0" style={{ background: p.color }} />
                  <div className="flex-1 min-w-0">
                    <div className="text-sm font-medium text-gray-800 truncate">{p.title}</div>
                    <div className="text-[11px] text-gray-400">{p.description.slice(0, 50)}...</div>
                  </div>
                  <div className={`text-xs font-semibold px-2 py-1 rounded-lg ${diff <= 3 ? 'bg-red-50 text-red-600' : diff <= 7 ? 'bg-orange-50 text-orange-600' : 'bg-gray-100 text-gray-600'}`}>
                    {diff <= 0 ? 'Terlambat!' : diff === 1 ? 'Besok' : `${diff} hari lagi`}
                  </div>
                </div>
              )
            })}
        </div>
      </div>
    </div>
  )
}
