"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { CalendarOff, MoreHorizontal, Sparkles, Trash2, Wrench, DoorOpen } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useConfirm } from "@/components/ui/confirm";
import { StatusBadge } from "@/components/ui/badge";
import { EmptyState } from "@/components/ui/states";
import { fmtDate, fmtRange } from "@/lib/dates";
import { CLEANING_STATUSES, CLEANING_STATUS_META } from "@/lib/domain";
import { setApartmentStatus, setCleaningStatus, unblockDates, deleteApartment } from "@/lib/actions/apartments";
import { MaintenanceDialog } from "@/components/operations/maintenance-dialog";
import { BlockDatesDialog } from "@/components/inventory/inventory-dialogs";

export function ApartmentControls({ apartment, perms, staff }: { apartment: { id: string; code: string; status: string; cleaningStatus: string }; perms: { edit: boolean; cleaning: boolean; block: boolean; maintenance: boolean }; staff: { id: string; fullName: string }[] }) {
  const router = useRouter();
  const confirm = useConfirm();
  const [blockOpen, setBlockOpen] = React.useState(false);
  const [mntOpen, setMntOpen] = React.useState(false);

  async function cleaning(s: (typeof CLEANING_STATUSES)[number]) {
    const res = await setCleaningStatus(apartment.id, s);
    if (!res.ok) return toast.error(res.error);
    toast.success(`Cleaning: ${CLEANING_STATUS_META[s].label}`);
    router.refresh();
  }
  async function status(s: "AVAILABLE" | "MAINTENANCE" | "BLOCKED") {
    const { ok, reason } = await confirm({ title: `Set ${apartment.code} to ${s.toLowerCase()}?`, description: s === "AVAILABLE" ? "The status will follow reservations again." : "The apartment is removed from availability until changed back.", destructive: s !== "AVAILABLE", requireReason: s !== "AVAILABLE" });
    if (!ok) return;
    const res = await setApartmentStatus(apartment.id, s, reason);
    if (!res.ok) return toast.error(res.error);
    toast.success("Status updated");
    router.refresh();
  }
  async function remove() {
    const { ok, reason } = await confirm({ title: `Delete ${apartment.code}?`, description: "The apartment is archived and hidden. History is kept.", destructive: true, requireReason: true, confirmLabel: "Delete" });
    if (!ok) return;
    const res = await deleteApartment(apartment.id, reason ?? "");
    if (!res.ok) return toast.error(res.error);
    toast.success("Apartment deleted");
    router.push("/apartments");
  }

  return (
    <>
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="secondary" size="icon" aria-label="Apartment actions">
            <MoreHorizontal />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-60">
          {perms.cleaning ? (
            <>
              <DropdownMenuLabel>Cleaning</DropdownMenuLabel>
              {CLEANING_STATUSES.map((s) => (
                <DropdownMenuItem key={s} onSelect={() => cleaning(s)} disabled={apartment.cleaningStatus === s}>
                  <Sparkles /> {CLEANING_STATUS_META[s].label}
                </DropdownMenuItem>
              ))}
              <DropdownMenuSeparator />
            </>
          ) : null}
          {perms.block ? (
            <DropdownMenuItem onSelect={() => setBlockOpen(true)}>
              <CalendarOff /> Block dates
            </DropdownMenuItem>
          ) : null}
          {perms.maintenance ? (
            <DropdownMenuItem onSelect={() => setMntOpen(true)}>
              <Wrench /> Report maintenance issue
            </DropdownMenuItem>
          ) : null}
          {perms.edit ? (
            <>
              <DropdownMenuSeparator />
              <DropdownMenuLabel>Status</DropdownMenuLabel>
              <DropdownMenuItem onSelect={() => status("AVAILABLE")} disabled={!["MAINTENANCE", "BLOCKED"].includes(apartment.status)}>
                <DoorOpen /> Back to available
              </DropdownMenuItem>
              <DropdownMenuItem onSelect={() => status("MAINTENANCE")} disabled={apartment.status === "MAINTENANCE"}>
                <Wrench /> Under maintenance
              </DropdownMenuItem>
              <DropdownMenuItem onSelect={() => status("BLOCKED")} disabled={apartment.status === "BLOCKED"}>
                <CalendarOff /> Blocked
              </DropdownMenuItem>
              <DropdownMenuSeparator />
              <DropdownMenuItem destructive onSelect={remove}>
                <Trash2 /> Delete apartment
              </DropdownMenuItem>
            </>
          ) : null}
        </DropdownMenuContent>
      </DropdownMenu>

      <Dialog open={blockOpen} onOpenChange={setBlockOpen}>
        <DialogContent size="lg">{blockOpen ? <BlockDatesDialog apartments={[{ id: apartment.id, code: apartment.code, name: "" }]} presetApartmentId={apartment.id} currency="MAD" onClose={() => setBlockOpen(false)} /> : null}</DialogContent>
      </Dialog>

      <MaintenanceDialog open={mntOpen} onOpenChange={setMntOpen} apartments={[{ id: apartment.id, code: apartment.code, name: "" }]} staff={staff} presetApartmentId={apartment.id} />
    </>
  );
}

export function BlockList({ blocks, canManage }: { blocks: { id: string; startDate: string; endDate: string; reason: string | null; type: string }[]; canManage: boolean }) {
  const router = useRouter();
  const confirm = useConfirm();
  async function remove(id: string) {
    const { ok } = await confirm({ title: "Remove this block?", description: "The dates become available again.", confirmLabel: "Remove" });
    if (!ok) return;
    const res = await unblockDates(id);
    if (!res.ok) return toast.error(res.error);
    toast.success("Block removed");
    router.refresh();
  }
  if (blocks.length === 0) return <EmptyState compact icon={CalendarOff} title="No blocked dates" description="Block dates for owner use, renovation or maintenance." />;
  return (
    <ul className="divide-y divide-border">
      {blocks.map((b) => (
        <li key={b.id} className="flex items-center gap-3 py-2.5 text-sm">
          <CalendarOff className="size-4 text-fg-subtle" />
          <span className="min-w-0 flex-1">
            <span className="block font-medium">{fmtRange(b.startDate, b.endDate)}</span>
            <span className="block text-xs text-fg-muted">
              {b.reason ?? "No reason given"} · from {fmtDate(b.startDate)} until {fmtDate(b.endDate)}
            </span>
          </span>
          <StatusBadge status={b.type === "MAINTENANCE" ? "MAINTENANCE" : "MANUAL"} size="sm" />
          {canManage && b.type === "MANUAL" ? (
            <Button variant="ghost" size="iconXs" className="text-negative-600" onClick={() => remove(b.id)} aria-label="Remove block">
              <Trash2 />
            </Button>
          ) : null}
        </li>
      ))}
    </ul>
  );
}
