"use client";

import { useState, useMemo } from "react";
import Link from "next/link";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge, statutBadgeVariant } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogClose,
} from "@/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  formatDate,
  formatMoney,
  STATUT_RESERVATION_LABELS,
  TYPE_CHAMBRE_LABELS,
} from "@/lib/utils";
import { ChevronLeft, ChevronRight } from "lucide-react";

interface Event {
  id: string;
  client: string;
  chambre: string;
  type: string;
  arrivee: string;
  depart: string;
  statut: string;
  nb_nuits: number;
  prix_total: number;
}

type View = "month" | "week" | "day";

const STATUT_COLORS: Record<string, string> = {
  CONFIRMEE: "#2563EB",
  EN_ATTENTE: "#D97706",
  TERMINEE: "#374151",
  ANNULEE: "#FCA5A5",
};

const MONTH_NAMES = [
  "Janvier", "Février", "Mars", "Avril", "Mai", "Juin",
  "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre",
];
const DAY_NAMES = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];

export function CalendrierView({ events }: { events: Event[] }) {
  const [cursor, setCursor] = useState(new Date());
  const [view, setView] = useState<View>("month");
  const [selectedEvent, setSelectedEvent] = useState<Event | null>(null);

  const eventsByDate = useMemo(() => {
    const map = new Map<string, Event[]>();
    for (const ev of events) {
      const start = new Date(ev.arrivee);
      const end = new Date(ev.depart);
      const cur = new Date(start);
      cur.setHours(0, 0, 0, 0);
      while (cur < end) {
        const key = cur.toISOString().split("T")[0];
        if (!map.has(key)) map.set(key, []);
        map.get(key)!.push(ev);
        cur.setDate(cur.getDate() + 1);
      }
    }
    return map;
  }, [events]);

  function prev() {
    const d = new Date(cursor);
    if (view === "month") d.setMonth(d.getMonth() - 1);
    else if (view === "week") d.setDate(d.getDate() - 7);
    else d.setDate(d.getDate() - 1);
    setCursor(d);
  }
  function next() {
    const d = new Date(cursor);
    if (view === "month") d.setMonth(d.getMonth() + 1);
    else if (view === "week") d.setDate(d.getDate() + 7);
    else d.setDate(d.getDate() + 1);
    setCursor(d);
  }
  function today() {
    setCursor(new Date());
  }

  const title = useMemo(() => {
    if (view === "month") return `${MONTH_NAMES[cursor.getMonth()]} ${cursor.getFullYear()}`;
    if (view === "day")
      return cursor.toLocaleDateString("fr-FR", {
        weekday: "long", day: "numeric", month: "long", year: "numeric",
      });
    // Week
    const start = new Date(cursor);
    start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
    const end = new Date(start);
    end.setDate(end.getDate() + 6);
    return `${formatDate(start)} - ${formatDate(end)}`;
  }, [cursor, view]);

  return (
    <Card>
      <CardContent className="p-4 lg:p-6">
        {/* Header navigation */}
        <div className="flex items-center justify-between gap-3 flex-wrap mb-4">
          <h3 className="text-lg font-semibold">{title}</h3>
          <div className="flex items-center gap-2">
            <Tabs value={view} onValueChange={(v) => setView(v as View)}>
              <TabsList>
                <TabsTrigger value="month">Mois</TabsTrigger>
                <TabsTrigger value="week">Semaine</TabsTrigger>
                <TabsTrigger value="day">Jour</TabsTrigger>
              </TabsList>
            </Tabs>
            <Button variant="outline" size="sm" onClick={today}>
              Aujourd&apos;hui
            </Button>
            <Button variant="outline" size="icon" onClick={prev}>
              <ChevronLeft className="w-4 h-4" />
            </Button>
            <Button variant="outline" size="icon" onClick={next}>
              <ChevronRight className="w-4 h-4" />
            </Button>
          </div>
        </div>

        {view === "month" && (
          <MonthView cursor={cursor} eventsByDate={eventsByDate} onClick={setSelectedEvent} />
        )}
        {view === "week" && (
          <WeekView cursor={cursor} eventsByDate={eventsByDate} onClick={setSelectedEvent} />
        )}
        {view === "day" && (
          <DayView cursor={cursor} eventsByDate={eventsByDate} onClick={setSelectedEvent} />
        )}

        {/* Légende */}
        <div className="flex flex-wrap gap-3 mt-4 pt-4 border-t text-xs">
          <span className="font-medium text-muted-foreground">Légende :</span>
          {Object.entries(STATUT_COLORS).map(([statut, color]) => (
            <span key={statut} className="flex items-center gap-1.5">
              <span
                className="w-3 h-3 rounded-sm"
                style={{ backgroundColor: color }}
              />
              {STATUT_RESERVATION_LABELS[statut]}
            </span>
          ))}
        </div>
      </CardContent>

      {/* Modale détails */}
      <Dialog open={!!selectedEvent} onOpenChange={() => setSelectedEvent(null)}>
        <DialogContent>
          {selectedEvent && (
            <>
              <DialogHeader>
                <DialogTitle>{selectedEvent.client}</DialogTitle>
                <DialogDescription>
                  Chambre {selectedEvent.chambre} ({TYPE_CHAMBRE_LABELS[selectedEvent.type]})
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Arrivée</span>
                  <span>{formatDate(selectedEvent.arrivee)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Départ</span>
                  <span>{formatDate(selectedEvent.depart)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Nuits</span>
                  <span>{selectedEvent.nb_nuits}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Prix total</span>
                  <span className="font-semibold">
                    {formatMoney(selectedEvent.prix_total)}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">Statut</span>
                  <Badge variant={statutBadgeVariant(selectedEvent.statut)}>
                    {STATUT_RESERVATION_LABELS[selectedEvent.statut]}
                  </Badge>
                </div>
              </div>
              <DialogFooter>
                <DialogClose asChild>
                  <Button variant="outline">Fermer</Button>
                </DialogClose>
                <Button asChild variant="accent">
                  <Link href={`/reservations/${selectedEvent.id}`}>
                    Voir la réservation
                  </Link>
                </Button>
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>
    </Card>
  );
}

function MonthView({
  cursor,
  eventsByDate,
  onClick,
}: {
  cursor: Date;
  eventsByDate: Map<string, Event[]>;
  onClick: (e: Event) => void;
}) {
  const year = cursor.getFullYear();
  const month = cursor.getMonth();
  const firstOfMonth = new Date(year, month, 1);
  const lastOfMonth = new Date(year, month + 1, 0);

  // Lundi = 1ère colonne (en France)
  const startOffset = (firstOfMonth.getDay() + 6) % 7;
  const totalCells = Math.ceil((startOffset + lastOfMonth.getDate()) / 7) * 7;
  const cells: (Date | null)[] = [];
  for (let i = 0; i < totalCells; i++) {
    const dayNum = i - startOffset + 1;
    if (dayNum < 1 || dayNum > lastOfMonth.getDate()) {
      cells.push(null);
    } else {
      cells.push(new Date(year, month, dayNum));
    }
  }

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  return (
    <div>
      <div className="grid grid-cols-7 gap-1 mb-1">
        {DAY_NAMES.map((d) => (
          <div key={d} className="text-xs font-semibold text-muted-foreground text-center py-2">
            {d}
          </div>
        ))}
      </div>
      <div className="grid grid-cols-7 gap-1">
        {cells.map((date, idx) => {
          if (!date) return <div key={idx} className="aspect-square" />;
          const key = date.toISOString().split("T")[0];
          const dayEvents = eventsByDate.get(key) || [];
          const isToday = date.getTime() === today.getTime();
          return (
            <div
              key={idx}
              className={`border rounded-md p-1 min-h-[90px] ${isToday ? "border-accent border-2" : "border-border"}`}
            >
              <div
                className={`text-xs font-semibold mb-1 ${isToday ? "text-accent" : ""}`}
              >
                {date.getDate()}
              </div>
              <div className="space-y-0.5">
                {dayEvents.slice(0, 3).map((ev) => (
                  <button
                    key={`${ev.id}-${key}`}
                    onClick={() => onClick(ev)}
                    className="w-full text-left text-[10px] px-1.5 py-0.5 rounded truncate text-white hover:opacity-90"
                    style={{ backgroundColor: STATUT_COLORS[ev.statut] || "#6B7280" }}
                  >
                    Ch.{ev.chambre} {ev.client.split(" ")[0]}
                  </button>
                ))}
                {dayEvents.length > 3 && (
                  <p className="text-[10px] text-muted-foreground px-1">
                    +{dayEvents.length - 3} autre(s)
                  </p>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function WeekView({
  cursor,
  eventsByDate,
  onClick,
}: {
  cursor: Date;
  eventsByDate: Map<string, Event[]>;
  onClick: (e: Event) => void;
}) {
  const start = new Date(cursor);
  start.setDate(start.getDate() - ((start.getDay() + 6) % 7));
  const days: Date[] = [];
  for (let i = 0; i < 7; i++) {
    const d = new Date(start);
    d.setDate(d.getDate() + i);
    days.push(d);
  }
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  return (
    <div className="grid grid-cols-7 gap-2">
      {days.map((date, i) => {
        const key = date.toISOString().split("T")[0];
        const dayEvents = eventsByDate.get(key) || [];
        const isToday = date.getTime() === today.getTime();
        return (
          <div key={i} className="space-y-1">
            <div
              className={`text-center p-2 rounded-md ${isToday ? "bg-accent text-white" : "bg-secondary"}`}
            >
              <div className="text-xs font-semibold">{DAY_NAMES[i]}</div>
              <div className="text-lg font-bold">{date.getDate()}</div>
            </div>
            <div className="space-y-1 min-h-[200px]">
              {dayEvents.map((ev) => (
                <button
                  key={`${ev.id}-${key}`}
                  onClick={() => onClick(ev)}
                  className="w-full text-left text-xs p-2 rounded text-white hover:opacity-90"
                  style={{ backgroundColor: STATUT_COLORS[ev.statut] || "#6B7280" }}
                >
                  <p className="font-semibold truncate">Ch. {ev.chambre}</p>
                  <p className="truncate opacity-90">{ev.client}</p>
                </button>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

function DayView({
  cursor,
  eventsByDate,
  onClick,
}: {
  cursor: Date;
  eventsByDate: Map<string, Event[]>;
  onClick: (e: Event) => void;
}) {
  const key = cursor.toISOString().split("T")[0];
  const dayEvents = eventsByDate.get(key) || [];

  if (dayEvents.length === 0) {
    return (
      <div className="text-center py-12 text-muted-foreground">
        Aucune réservation pour ce jour.
      </div>
    );
  }

  return (
    <div className="space-y-2">
      {dayEvents.map((ev) => (
        <button
          key={ev.id}
          onClick={() => onClick(ev)}
          className="w-full text-left p-4 rounded-lg border hover:shadow-md transition-shadow flex items-center gap-4"
        >
          <div
            className="w-2 h-12 rounded-full"
            style={{ backgroundColor: STATUT_COLORS[ev.statut] || "#6B7280" }}
          />
          <div className="flex-1">
            <p className="font-semibold">{ev.client}</p>
            <p className="text-sm text-muted-foreground">
              Chambre {ev.chambre} · {TYPE_CHAMBRE_LABELS[ev.type]} · {ev.nb_nuits} nuit(s)
            </p>
          </div>
          <Badge variant={statutBadgeVariant(ev.statut)}>
            {STATUT_RESERVATION_LABELS[ev.statut]}
          </Badge>
        </button>
      ))}
    </div>
  );
}
