"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { Badge, Button, buttonClass } from "@/components/ui";
import { deleteReportFilterAction, deleteReportScheduleAction, setReportScheduleEnabledAction } from "@/lib/actions/reports";

const date = (iso: string | null) => (iso ? iso.slice(0, 16).replace("T", " ") : "Never");
const th = "whitespace-nowrap px-4 py-2 font-medium";

function useRun() {
  const router = useRouter();
  const [pending, start] = useTransition();
  const [armed, setArmed] = useState<string | null>(null);
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
  const run = (f: () => Promise<{ ok: boolean; message?: string; error?: string }>) => start(async () => { const r = await f(); setMsg({ ok: r.ok, text: r.ok ? (r.message ?? "Saved") : (r.error ?? "Failed") }); setArmed(null); if (r.ok) router.refresh(); });
  const status = <p role="status" aria-live="polite" className={msg ? (msg.ok ? "px-4 py-2 text-sm text-success" : "px-4 py-2 text-sm text-danger") : "sr-only"}>{msg?.text}</p>;
  return { pending, armed, setArmed, run, status };
}

export interface SavedFilterItem { id: string; name: string; entity: string; entityLabel: string; filterCount: number; createdAt: string }

export function SavedFiltersTable({ siteId, base, rows }: { siteId: string; base: string; rows: SavedFilterItem[] }) {
  const { pending, armed, setArmed, run, status } = useRun();
  return (
    <>
      {status}
      <div className="overflow-x-auto" tabIndex={0} role="region" aria-label="Saved filters table">
        <table className="w-full text-left text-sm">
          <caption className="sr-only">Saved filters</caption>
          <thead className="border-b border-border text-xs text-muted-foreground"><tr><th scope="col" className={th}>Name</th><th scope="col" className={th}>Report</th><th scope="col" className={th}>Filters</th><th scope="col" className={th}>Date created</th><th scope="col" className={th}><span className="sr-only">Actions</span></th></tr></thead>
          <tbody className="divide-y divide-border">
            {rows.map((r) => (
              <tr key={r.id}>
                <td className="px-4 py-2 font-medium">{r.name}</td><td className="px-4 py-2">{r.entityLabel}</td><td className="px-4 py-2">{r.filterCount}</td><td className="whitespace-nowrap px-4 py-2">{date(r.createdAt)}</td>
                <td className="px-4 py-2"><div className="flex justify-end gap-2">
                  <Link href={`${base}/run?entity=${encodeURIComponent(r.entity)}&filter=${r.id}`} className={buttonClass("secondary")} aria-label={`Open ${r.name}`}>Open</Link>
                  {armed === r.id ? (<><Button variant="danger" disabled={pending} onClick={() => run(() => deleteReportFilterAction(siteId, r.id))}>Confirm delete</Button><Button variant="ghost" onClick={() => setArmed(null)}>Cancel</Button></>) : <Button variant="ghost" aria-label={`Delete ${r.name}`} onClick={() => setArmed(r.id)}>Delete</Button>}
                </div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}

export interface ScheduleItem { id: string; name: string; entityLabel: string; filterName: string; frequency: string; recipients: string[]; enabled: boolean; lastRanAt: string | null; nextRunAt: string; createdAt: string }

export function SchedulesTable({ siteId, rows }: { siteId: string; rows: ScheduleItem[] }) {
  const { pending, armed, setArmed, run, status } = useRun();
  return (
    <>
      {status}
      <div className="overflow-x-auto" tabIndex={0} role="region" aria-label="Saved schedules table">
        <table className="w-full text-left text-sm">
          <caption className="sr-only">Saved schedules</caption>
          <thead className="border-b border-border text-xs text-muted-foreground"><tr><th scope="col" className={th}>Name</th><th scope="col" className={th}>Entity</th><th scope="col" className={th}>Date created</th><th scope="col" className={th}>Schedule</th><th scope="col" className={th}>Last ran</th><th scope="col" className={th}><span className="sr-only">Actions</span></th></tr></thead>
          <tbody className="divide-y divide-border">
            {rows.map((r) => (
              <tr key={r.id}>
                <td className="px-4 py-2"><span className="font-medium">{r.name}</span>{r.filterName ? <span className="block text-xs text-muted-foreground">Filter: {r.filterName}</span> : <span className="block text-xs text-danger">Saved filter was deleted</span>}</td>
                <td className="px-4 py-2">{r.entityLabel}</td><td className="whitespace-nowrap px-4 py-2">{date(r.createdAt)}</td>
                <td className="px-4 py-2">{r.frequency[0] + r.frequency.slice(1).toLowerCase()} {r.enabled ? <span className="block text-xs text-muted-foreground">Next: {date(r.nextRunAt)} UTC</span> : <Badge tone="warning">Paused</Badge>}</td>
                <td className="whitespace-nowrap px-4 py-2">{date(r.lastRanAt)}</td>
                <td className="px-4 py-2"><div className="flex justify-end gap-2">
                  <Button variant="secondary" disabled={pending} aria-label={`${r.enabled ? "Pause" : "Resume"} ${r.name}`} onClick={() => run(() => setReportScheduleEnabledAction(siteId, r.id, !r.enabled))}>{r.enabled ? "Pause" : "Resume"}</Button>
                  {armed === r.id ? (<><Button variant="danger" disabled={pending} onClick={() => run(() => deleteReportScheduleAction(siteId, r.id))}>Confirm delete</Button><Button variant="ghost" onClick={() => setArmed(null)}>Cancel</Button></>) : <Button variant="ghost" aria-label={`Delete ${r.name}`} onClick={() => setArmed(r.id)}>Delete</Button>}
                </div></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
}
