"use client";

import { useState, useEffect } from "react";
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  PlusIcon,
  XMarkIcon,
} from "@heroicons/react/24/outline";
import { DatePickerInput } from "@/components/DatePickerInput";

type Booking = {
  id: string;
  name: string;
  from: string;
  to: string;
  color: string;
};

const COLORS = [
  "#0ea5e9",
  "#10b981",
  "#f59e0b",
  "#ef4444",
  "#8b5cf6",
  "#ec4899",
  "#14b8a6",
  "#f97316",
  "#6366f1",
  "#84cc16",
];

const MONTH_NAMES = [
  "Januar", "Februar", "Mart", "April", "Maj", "Jun",
  "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar",
];
const DAY_NAMES = ["Pon", "Uto", "Sre", "Čet", "Pet", "Sub", "Ned"];

function toYMD(d: Date) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}-${m}-${day}`;
}

function getDaysInMonth(year: number, month: number) {
  return new Date(year, month + 1, 0).getDate();
}

function getFirstDow(year: number, month: number) {
  const dow = new Date(year, month, 1).getDay();
  return (dow + 6) % 7; // Monday = 0
}

function fmtDisplay(ymd: string) {
  const [y, m, d] = ymd.split("-");
  return `${d}.${m}.${y}`;
}

// Converts dd.mm.yyyy → yyyy-mm-dd; returns null if invalid
function parseInputDate(s: string): string | null {
  const match = s.trim().match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);
  if (!match) return null;
  const [, d, m, y] = match;
  const date = new Date(Number(y), Number(m) - 1, Number(d));
  if (isNaN(date.getTime())) return null;
  return `${y}-${m.padStart(2, "0")}-${d.padStart(2, "0")}`;
}

export function BookingCalendar({ isAdmin }: { isAdmin: boolean }) {
  const today = new Date();
  const [year, setYear] = useState(today.getFullYear());
  const [month, setMonth] = useState(today.getMonth());
  const [bookings, setBookings] = useState<Booking[]>([]);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ name: "", from: "", to: "" });
  const [formError, setFormError] = useState("");
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetch("/api/bookings")
      .then((r) => r.json())
      .then((d) => setBookings(d.bookings ?? []));
  }, []);

  function prevMonth() {
    if (month === 0) { setMonth(11); setYear((y) => y - 1); }
    else setMonth((m) => m - 1);
  }
  function nextMonth() {
    if (month === 11) { setMonth(0); setYear((y) => y + 1); }
    else setMonth((m) => m + 1);
  }

  function bookingsForDay(day: number): Booking[] {
    const d = toYMD(new Date(year, month, day));
    return bookings.filter((b) => b.from <= d && d <= b.to);
  }

  async function saveBookings(updated: Booking[]) {
    setSaving(true);
    await fetch("/api/bookings", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ bookings: updated }),
    });
    setBookings(updated);
    setSaving(false);
  }

  async function addBooking() {
    setFormError("");
    if (!form.name.trim() || !form.from || !form.to) {
      setFormError("Popunite sva polja.");
      return;
    }
    const fromYMD = parseInputDate(form.from);
    const toYMD = parseInputDate(form.to);
    if (!fromYMD || !toYMD) {
      setFormError("Format datuma mora biti dd.mm.yyyy");
      return;
    }
    if (fromYMD > toYMD) {
      setFormError("Datum 'Od' mora biti prije datuma 'Do'.");
      return;
    }
    const overlap = bookings.find((b) => fromYMD <= b.to && b.from <= toYMD);
    if (overlap) {
      setFormError(`Period se preklapa sa boravkom: ${overlap.name} (${fmtDisplay(overlap.from)} – ${fmtDisplay(overlap.to)})`);
      return;
    }
    const color = COLORS[bookings.length % COLORS.length];
    const newBooking: Booking = { id: Date.now().toString(), name: form.name.trim(), from: fromYMD, to: toYMD, color };
    await saveBookings([...bookings, newBooking]);
    setForm({ name: "", from: "", to: "" });
    setShowForm(false);
  }

  async function removeBooking(id: string) {
    await saveBookings(bookings.filter((b) => b.id !== id));
  }

  const daysInMonth = getDaysInMonth(year, month);
  const firstDow = getFirstDow(year, month);
  const cells: (number | null)[] = [
    ...Array(firstDow).fill(null),
    ...Array.from({ length: daysInMonth }, (_, i) => i + 1),
  ];

  return (
    <section className="bg-sky-50 border-y border-sky-100">
      <div className="max-w-5xl mx-auto px-4 py-12">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-2xl font-bold text-sky-800">Kalendar boravka</h2>
          {isAdmin && (
            <button
              onClick={() => setShowForm((v) => !v)}
              className="flex items-center gap-1.5 bg-sky-600 text-white px-4 py-2 rounded-full text-sm font-semibold hover:bg-sky-700 transition-colors"
            >
              <PlusIcon className="w-4 h-4" />
              Dodaj boravak
            </button>
          )}
        </div>

        {showForm && isAdmin && (
          <div className="bg-white rounded-2xl border border-sky-100 shadow-sm p-5 mb-6 flex flex-wrap gap-4 items-end">
            <div>
              <label className="block text-xs text-gray-500 mb-1 font-medium">Ime</label>
              <input
                className="border border-gray-200 rounded-lg px-3 py-2 text-sm w-36 focus:outline-none focus:ring-2 focus:ring-sky-300"
                value={form.name}
                onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
                placeholder="Milan"
              />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1 font-medium">Od</label>
              <DatePickerInput
                value={form.from}
                onChange={(v) => setForm((f) => ({ ...f, from: v }))}
              />
            </div>
            <div>
              <label className="block text-xs text-gray-500 mb-1 font-medium">Do</label>
              <DatePickerInput
                value={form.to}
                onChange={(v) => setForm((f) => ({ ...f, to: v }))}
              />
            </div>
            <div className="flex flex-col gap-1">
              {formError && <p className="text-xs text-red-500">{formError}</p>}
              <div className="flex gap-2">
                <button
                  onClick={addBooking}
                  disabled={saving}
                  className="bg-sky-600 text-white px-5 py-2 rounded-lg text-sm font-semibold hover:bg-sky-700 transition-colors disabled:opacity-50"
                >
                  Sačuvaj
                </button>
                <button
                  onClick={() => { setShowForm(false); setFormError(""); }}
                  className="text-gray-400 hover:text-gray-600 text-sm"
                >
                  Odustani
                </button>
              </div>
            </div>
          </div>
        )}

        <div className="bg-white rounded-2xl shadow-sm border border-sky-100 overflow-hidden">
          <div className="flex items-center justify-between px-6 py-4 bg-sky-600 text-white">
            <button
              onClick={prevMonth}
              className="p-1 rounded hover:bg-sky-500 transition-colors"
            >
              <ChevronLeftIcon className="w-5 h-5" />
            </button>
            <span className="font-semibold text-lg">
              {MONTH_NAMES[month]} {year}
            </span>
            <button
              onClick={nextMonth}
              className="p-1 rounded hover:bg-sky-500 transition-colors"
            >
              <ChevronRightIcon className="w-5 h-5" />
            </button>
          </div>

          <div className="grid grid-cols-7 border-b border-gray-100">
            {DAY_NAMES.map((d) => (
              <div key={d} className="text-center text-xs font-semibold text-gray-400 py-2">
                {d}
              </div>
            ))}
          </div>

          <div className="grid grid-cols-7">
            {cells.map((day, i) => {
              if (!day) {
                return (
                  <div
                    key={`e-${i}`}
                    className="min-h-[72px] border-r border-b border-gray-50 bg-gray-50/40"
                  />
                );
              }
              const dayBookings = bookingsForDay(day);
              const isToday =
                year === today.getFullYear() &&
                month === today.getMonth() &&
                day === today.getDate();
              return (
                <div
                  key={day}
                  className={`min-h-[72px] border-r border-b border-gray-50 p-1 ${isToday ? "bg-sky-50" : ""}`}
                >
                  <div
                    className={`text-xs font-semibold mb-1 w-6 h-6 flex items-center justify-center rounded-full ${
                      isToday ? "bg-sky-600 text-white" : "text-gray-500"
                    }`}
                  >
                    {day}
                  </div>
                  <div className="flex flex-col gap-0.5">
                    {dayBookings.map((b) => (
                      <div
                        key={b.id}
                        className="text-xs px-1.5 py-0.5 rounded text-white font-medium truncate leading-tight"
                        style={{ backgroundColor: b.color }}
                        title={b.name}
                      >
                        {b.name}
                      </div>
                    ))}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {bookings.filter((b) => b.to >= toYMD(today)).length > 0 && (
          <div className="mt-4 flex flex-wrap gap-2">
            {bookings.filter((b) => b.to >= toYMD(today)).map((b) => (
              <div
                key={b.id}
                className="flex items-center gap-2 bg-white border border-gray-100 rounded-full px-3 py-1.5 text-sm shadow-sm"
              >
                <span
                  className="w-2.5 h-2.5 rounded-full flex-shrink-0"
                  style={{ backgroundColor: b.color }}
                />
                <span className="font-semibold text-gray-700">{b.name}</span>
                <span className="text-gray-400 text-xs">
                  {fmtDisplay(b.from)} – {fmtDisplay(b.to)}
                </span>
                {isAdmin && (
                  <button
                    onClick={() => removeBooking(b.id)}
                    className="text-gray-300 hover:text-red-400 transition-colors ml-0.5"
                    title="Ukloni"
                  >
                    <XMarkIcon className="w-3.5 h-3.5" />
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
