"use client";

import { useState, useRef } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import trLocale from "@fullcalendar/core/locales/tr";
import { Plus } from "lucide-react";
import { calendarApi } from "@/lib/api";
import { CalendarEvent } from "@/types";
import { PageHeader, Modal, Spinner } from "@/components/ui";
import { useForm } from "react-hook-form";
import toast from "react-hot-toast";

function EventForm({
  event,
  defaultStart,
  onClose,
}: {
  event?: CalendarEvent;
  defaultStart?: string;
  onClose: () => void;
}) {
  const qc = useQueryClient();
  const { register, handleSubmit } = useForm({
    defaultValues: event
      ? {
          title: event.title,
          description: event.description || "",
          start_datetime: event.start_datetime.slice(0, 16),
          end_datetime: event.end_datetime?.slice(0, 16) || "",
          all_day: event.all_day,
          color: event.color,
        }
      : {
          start_datetime: defaultStart || new Date().toISOString().slice(0, 16),
          color: "#3b82f6",
          all_day: false,
        },
  });

  const mutation = useMutation({
    mutationFn: (data: Record<string, unknown>) =>
      event ? calendarApi.update(event.id, data) : calendarApi.create(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["calendar-events"] });
      toast.success(event ? "Etkinlik güncellendi." : "Etkinlik oluşturuldu.");
      onClose();
    },
  });

  return (
    <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-4">
      <div>
        <label className="form-label">Etkinlik Başlığı *</label>
        <input {...register("title", { required: true })} className="kaplan-input" placeholder="Etkinlik başlığı" />
      </div>
      <div>
        <label className="form-label">Açıklama</label>
        <textarea {...register("description")} rows={3} className="kaplan-textarea" placeholder="Etkinlik açıklaması..." />
      </div>
      <div className="grid grid-cols-2 gap-3">
        <div>
          <label className="form-label">Başlangıç</label>
          <input {...register("start_datetime", { required: true })} type="datetime-local" className="kaplan-input" />
        </div>
        <div>
          <label className="form-label">Bitiş</label>
          <input {...register("end_datetime")} type="datetime-local" className="kaplan-input" />
        </div>
      </div>
      <div className="flex items-center gap-4">
        <div className="flex items-center gap-2">
          <input {...register("all_day")} type="checkbox" id="allDay" className="w-4 h-4 rounded" />
          <label htmlFor="allDay" className="text-sm text-surface-400 cursor-pointer">Tüm gün</label>
        </div>
        <div className="flex items-center gap-2 ml-auto">
          <label className="form-label mb-0">Renk</label>
          <input {...register("color")} type="color" className="w-8 h-8 rounded cursor-pointer border border-surface-500" />
        </div>
      </div>
      <div className="flex gap-3 justify-end pt-2">
        <button type="button" onClick={onClose} className="btn-secondary">İptal</button>
        <button type="submit" disabled={mutation.isPending} className="btn-primary">
          {mutation.isPending && <Spinner size={14} />}
          {event ? "Güncelle" : "Oluştur"}
        </button>
      </div>
    </form>
  );
}

export default function TakvimPage() {
  const qc = useQueryClient();
  const calendarRef = useRef<FullCalendar>(null);
  const [modal, setModal] = useState<{
    open: boolean;
    event?: CalendarEvent;
    defaultStart?: string;
  }>({ open: false });

  const [dateRange, setDateRange] = useState({
    start: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString(),
    end: new Date(new Date().getFullYear(), new Date().getMonth() + 2, 0).toISOString(),
  });

  const { data: events = [], isLoading } = useQuery<CalendarEvent[]>({
    queryKey: ["calendar-events", dateRange.start, dateRange.end],
    queryFn: () => calendarApi.list(dateRange.start, dateRange.end),
  });

  const deleteMutation = useMutation({
    mutationFn: (id: number) => calendarApi.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["calendar-events"] });
      toast.success("Etkinlik silindi.");
    },
  });

  // FullCalendar için events formatı
  const fcEvents = events.map((e) => ({
    id: String(e.id),
    title: e.title,
    start: e.start_datetime,
    end: e.end_datetime || undefined,
    allDay: e.all_day,
    backgroundColor: e.color + "33",
    borderColor: e.color,
    textColor: e.color,
    extendedProps: { original: e },
  }));

  return (
    <div className="space-y-5 animate-fade-in">
      <PageHeader
        title="Takvim"
        subtitle="Etkinliklerinizi, görevlerinizi ve projelerinizi planlayın"
        action={
          <button onClick={() => setModal({ open: true })} className="btn-primary">
            <Plus size={16} /> Yeni Etkinlik
          </button>
        }
      />

      <div className="kaplan-card p-0 overflow-hidden">
        <div className="p-4">
          {isLoading && (
            <div className="flex justify-center py-4">
              <Spinner />
            </div>
          )}
          <FullCalendar
            ref={calendarRef}
            plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
            initialView="dayGridMonth"
            locale={trLocale}
            events={fcEvents}
            headerToolbar={{
              left: "prev,next today",
              center: "title",
              right: "dayGridMonth,timeGridWeek,timeGridDay",
            }}
            height="calc(100vh - 260px)"
            selectable={true}
            editable={false}
            eventClick={(info) => {
              const original = info.event.extendedProps.original as CalendarEvent;
              setModal({ open: true, event: original });
            }}
            select={(info) => {
              setModal({
                open: true,
                defaultStart: info.startStr.slice(0, 16),
              });
            }}
            datesSet={(info) => {
              setDateRange({ start: info.startStr, end: info.endStr });
            }}
            buttonText={{ today: "Bugün", month: "Ay", week: "Hafta", day: "Gün" }}
            dayHeaderClassNames="text-surface-500"
            dayCellClassNames="hover:bg-surface-600/20 transition-colors"
            eventClassNames="cursor-pointer hover:opacity-80 transition-opacity text-xs font-medium rounded"
            nowIndicatorClassNames="bg-brand-500"
          />
        </div>
      </div>

      <Modal
        open={modal.open}
        onClose={() => setModal({ open: false })}
        title={modal.event ? "Etkinliği Düzenle" : "Yeni Etkinlik"}
      >
        <EventForm
          event={modal.event}
          defaultStart={modal.defaultStart}
          onClose={() => setModal({ open: false })}
        />
        {modal.event && (
          <div className="px-6 pb-5 border-t border-surface-500 pt-4">
            <button
              onClick={() => {
                if (modal.event) {
                  deleteMutation.mutate(modal.event.id);
                  setModal({ open: false });
                }
              }}
              className="btn-danger text-sm w-full justify-center"
            >
              Etkinliği Sil
            </button>
          </div>
        )}
      </Modal>
    </div>
  );
}
