"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import FullCalendar from "@fullcalendar/react"
import dayGridPlugin from "@fullcalendar/daygrid"
import timeGridPlugin from "@fullcalendar/timegrid"
import listPlugin from "@fullcalendar/list"
import interactionPlugin from "@fullcalendar/interaction"
import type { EventClickArg, EventDropArg } from "@fullcalendar/core"
import { toast } from "sonner"
import { CreditCard, FileText, ClipboardList, X, CalendarDays, Copy, Check, ArrowRight } from "lucide-react"
import "./calendar.css"

type EventType = "rent" | "lease" | "inspection"

export interface CalEvent {
  id: string
  title: string
  start: string
  allDay: boolean
  backgroundColor: string
  borderColor: string
  editable: boolean
  extendedProps: {
    type: EventType
    entityId: string
    status?: string
    subtitle: string
    href: string
  }
}

const TYPE_META: Record<EventType, { label: string; color: string; Icon: typeof CreditCard }> = {
  rent: { label: "Rent", color: "#6366f1", Icon: CreditCard },
  lease: { label: "Leases", color: "#f59e0b", Icon: FileText },
  inspection: { label: "Inspections", color: "#14b8a6", Icon: ClipboardList },
}

export function CalendarClient({
  events,
  canWrite,
  subscribeUrl,
}: {
  events: CalEvent[]
  canWrite: boolean
  subscribeUrl: string
}) {
  const [mounted, setMounted] = useState(false)
  const [active, setActive] = useState<Record<EventType, boolean>>({ rent: true, lease: true, inspection: true })
  const [selected, setSelected] = useState<(CalEvent["extendedProps"] & { title: string; start: string }) | null>(null)
  const [showSubscribe, setShowSubscribe] = useState(false)

  useEffect(() => setMounted(true), [])

  const shown = events.filter((e) => active[e.extendedProps.type])

  function toggle(t: EventType) {
    setActive((a) => ({ ...a, [t]: !a[t] }))
  }

  function onEventClick(info: EventClickArg) {
    info.jsEvent.preventDefault()
    const p = info.event.extendedProps as CalEvent["extendedProps"]
    setSelected({ ...p, title: info.event.title, start: info.event.startStr })
  }

  async function onEventDrop(info: EventDropArg) {
    const { type, entityId } = info.event.extendedProps as CalEvent["extendedProps"]
    if (!canWrite || type === "lease") {
      info.revert()
      toast.error(type === "lease" ? "Lease end dates can't be moved here" : "You don't have permission to reschedule")
      return
    }
    const newDate = info.event.startStr.slice(0, 10)
    const endpoint = type === "rent" ? `/api/rent/${entityId}` : `/api/inspections/${entityId}`
    const body = type === "rent" ? { due_date: newDate } : { date: newDate }
    try {
      const res = await fetch(endpoint, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })
      if (res.ok) toast.success(`Rescheduled to ${newDate}`)
      else {
        info.revert()
        toast.error("Couldn't reschedule")
      }
    } catch {
      info.revert()
      toast.error("Network error")
    }
  }

  return (
    <div className="space-y-4">
      {/* Toolbar: filters + subscribe */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex flex-wrap items-center gap-2">
          {(Object.keys(TYPE_META) as EventType[]).map((t) => {
            const m = TYPE_META[t]
            const on = active[t]
            return (
              <button
                key={t}
                onClick={() => toggle(t)}
                className="flex items-center gap-2 rounded-lg border px-3 py-1.5 text-xs font-medium transition"
                style={{
                  borderColor: on ? m.color + "66" : "rgba(255,255,255,0.08)",
                  background: on ? m.color + "1a" : "transparent",
                  color: on ? "#fff" : "rgba(255,255,255,0.4)",
                }}
              >
                <span className="h-2 w-2 rounded-full" style={{ background: m.color, opacity: on ? 1 : 0.4 }} />
                {m.label}
              </button>
            )
          })}
        </div>
        <button
          onClick={() => setShowSubscribe(true)}
          className="flex items-center gap-2 rounded-lg border border-indigo-500/30 bg-indigo-500/10 px-3 py-1.5 text-xs font-semibold text-indigo-300 transition hover:bg-indigo-500/15"
        >
          <CalendarDays className="h-3.5 w-3.5" /> Subscribe / Sync
        </button>
      </div>

      {/* Calendar */}
      <div className="fc-dark rounded-2xl border border-white/[0.06] bg-[#16161f] p-3 sm:p-4">
        {mounted ? (
          <FullCalendar
            plugins={[dayGridPlugin, timeGridPlugin, listPlugin, interactionPlugin]}
            initialView="dayGridMonth"
            headerToolbar={{ left: "prev,next today", center: "title", right: "dayGridMonth,timeGridWeek,timeGridDay,listMonth" }}
            buttonText={{ today: "Today", month: "Month", week: "Week", day: "Day", list: "Agenda" }}
            events={shown}
            editable={canWrite}
            eventStartEditable={canWrite}
            eventDurationEditable={false}
            dayMaxEvents={4}
            height="auto"
            firstDay={0}
            eventClick={onEventClick}
            eventDrop={onEventDrop}
            noEventsText="Nothing scheduled"
          />
        ) : (
          <div className="flex h-[520px] items-center justify-center text-sm text-white/30">Loading calendar…</div>
        )}
      </div>

      {selected && <EventDetail ev={selected} onClose={() => setSelected(null)} />}
      {showSubscribe && <SubscribeModal url={subscribeUrl} onClose={() => setShowSubscribe(false)} />}
    </div>
  )
}

function EventDetail({ ev, onClose }: { ev: CalEvent["extendedProps"] & { title: string; start: string }; onClose: () => void }) {
  const m = TYPE_META[ev.type]
  const dateLabel = new Date(ev.start + "T12:00:00").toLocaleDateString("en-US", { weekday: "long", month: "long", day: "numeric", year: "numeric" })
  return (
    <div className="fixed inset-0 z-[300] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm" onClick={onClose}>
      <div className="w-full max-w-sm rounded-2xl border border-white/10 bg-[#16161f] p-5" onClick={(e) => e.stopPropagation()}>
        <div className="mb-4 flex items-start justify-between gap-3">
          <div className="flex items-center gap-3">
            <div className="flex h-9 w-9 items-center justify-center rounded-xl border" style={{ borderColor: m.color + "33", background: m.color + "1a", color: m.color }}>
              <m.Icon className="h-4 w-4" />
            </div>
            <div>
              <p className="text-sm font-semibold text-white">{ev.title}</p>
              <p className="text-xs text-white/40">{m.label}</p>
            </div>
          </div>
          <button onClick={onClose} className="text-white/30 transition hover:text-white"><X className="h-4 w-4" /></button>
        </div>
        <dl className="space-y-2 text-sm">
          <div className="flex justify-between gap-4"><dt className="text-white/40">Date</dt><dd className="text-white/80">{dateLabel}</dd></div>
          {ev.subtitle && <div className="flex justify-between gap-4"><dt className="text-white/40">Details</dt><dd className="text-right text-white/80">{ev.subtitle}</dd></div>}
          {ev.status && <div className="flex justify-between gap-4"><dt className="text-white/40">Status</dt><dd className="capitalize text-white/80">{ev.status}</dd></div>}
        </dl>
        <Link href={ev.href} className="mt-5 flex items-center justify-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white transition hover:bg-indigo-500">
          Open {m.label.toLowerCase()} <ArrowRight className="h-3.5 w-3.5" />
        </Link>
      </div>
    </div>
  )
}

function SubscribeModal({ url, onClose }: { url: string; onClose: () => void }) {
  const [copied, setCopied] = useState(false)
  const webcal = url.replace(/^https?:\/\//, "webcal://")
  return (
    <div className="fixed inset-0 z-[300] flex items-center justify-center bg-black/60 p-4 backdrop-blur-sm" onClick={onClose}>
      <div className="w-full max-w-lg rounded-2xl border border-white/10 bg-[#16161f] p-6" onClick={(e) => e.stopPropagation()}>
        <div className="mb-4 flex items-start justify-between">
          <div>
            <h3 className="text-base font-bold text-white">Subscribe to your calendar</h3>
            <p className="mt-1 text-xs text-white/45">One-way sync — new rent, lease, and inspection dates appear automatically in your calendar app.</p>
          </div>
          <button onClick={onClose} className="text-white/30 transition hover:text-white"><X className="h-4 w-4" /></button>
        </div>

        {url ? (
          <>
            <div className="flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.03] p-2">
              <input readOnly value={url} className="flex-1 bg-transparent px-2 text-xs text-white/70 outline-none" onFocus={(e) => e.currentTarget.select()} />
              <button
                onClick={() => { navigator.clipboard.writeText(url).catch(() => {}); setCopied(true); setTimeout(() => setCopied(false), 2000) }}
                className="flex items-center gap-1 rounded-md bg-indigo-600 px-2.5 py-1.5 text-xs font-semibold text-white transition hover:bg-indigo-500"
              >
                {copied ? <><Check className="h-3 w-3" /> Copied</> : <><Copy className="h-3 w-3" /> Copy</>}
              </button>
            </div>

            <div className="mt-4 space-y-2.5 text-xs text-white/55">
              <p><strong className="text-white/80">Google Calendar:</strong> Settings → Add calendar → <em>From URL</em> → paste the link.</p>
              <p><strong className="text-white/80">Apple Calendar:</strong> File → New Calendar Subscription → paste, or open <a href={webcal} className="text-indigo-400 hover:text-indigo-300">this webcal link</a>.</p>
              <p><strong className="text-white/80">Outlook:</strong> Add calendar → Subscribe from web → paste the link.</p>
            </div>

            <div className="mt-4 flex items-center justify-between border-t border-white/[0.06] pt-4">
              <p className="text-[11px] text-white/30">Keep this link private — anyone with it can view your dates.</p>
              <a href={url} download className="rounded-lg border border-white/10 px-3 py-1.5 text-xs font-medium text-white/70 transition hover:bg-white/[0.06]">Download .ics</a>
            </div>
          </>
        ) : (
          <p className="text-sm text-white/50">Your feed link isn&apos;t available yet. Refresh the page and try again.</p>
        )}
      </div>
    </div>
  )
}
