"use client";

import { useState } from "react";
import { Copy, Check, Trash2, Loader2, CalendarDays, Link, AlertTriangle } from "lucide-react";
import { PRIMARY_COLOR } from "@/lib/common";
import { CalendarSubscription } from "@/types/calendar";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";


interface CalendarSubscriptionListProps {
  subscriptions: CalendarSubscription[];
  loading: boolean;
  error: string | null;
  copiedId: number | null;
  deletingId: number | null;
  deleteError: string | null;
  onCopy: (sub: CalendarSubscription) => void;
  onDelete: (id: number) => void;
}

export function CalendarSubscriptionList({
  subscriptions,
  loading,
  error,
  copiedId,
  deletingId,
  deleteError,
  onCopy,
  onDelete,
}: CalendarSubscriptionListProps) {
  const [deleteTarget, setDeleteTarget] = useState<CalendarSubscription | null>(null);

  const handleConfirmDelete = () => {
    if (!deleteTarget) return;
    onDelete(deleteTarget.id);
    setDeleteTarget(null);
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-16 text-muted-foreground">
        <Loader2 className="h-5 w-5 animate-spin mr-2" />
        <span className="text-sm">Loading calendars…</span>
      </div>
    );
  }

  if (subscriptions.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <div
          className="mb-4 flex h-12 w-12 items-center justify-center rounded-full"
          style={{ backgroundColor: `hsl(var(--primary) / 0.07)` }}
        >
          <CalendarDays className="h-6 w-6" style={{ color: PRIMARY_COLOR }} />
        </div>
        <p className="text-sm font-semibold text-foreground">
          No calendar subscriptions yet
        </p>
        <p className="mt-1 text-xs text-muted-foreground">
          Create one to subscribe your cashflow data to any calendar app.
        </p>
      </div>
    );
  }

  return (
    <>
      <div>
        {deleteError && (
          <div className="mx-4 mt-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-600">
            {deleteError}
          </div>
        )}

        <div className="divide-y divide-border">
          {subscriptions.map((sub) => (
            <CalendarRow
              key={sub.id}
              sub={sub}
              isCopied={copiedId === sub.id}
              isDeleting={deletingId === sub.id}
              onCopy={onCopy}
              onDeleteClick={() => setDeleteTarget(sub)}
            />
          ))}
        </div>
      </div>

      {/* Destructive confirmation.
          Uses `AlertDialog` rather than a bare overlay: it announces as
          role="alertdialog", focuses Cancel first, traps focus, locks scroll,
          and cannot be dismissed by a stray click outside — all of which the
          hand-rolled version lacked, on a irreversible action. */}
      <AlertDialog
        open={Boolean(deleteTarget)}
        onOpenChange={(open) => !open && setDeleteTarget(null)}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete “{deleteTarget?.name}”?</AlertDialogTitle>
            <AlertDialogDescription>
              This removes the calendar subscription and cannot be undone.
            </AlertDialogDescription>
          </AlertDialogHeader>

          <Alert variant="warning">
            <AlertTriangle aria-hidden />
            <AlertDescription>
              If you already subscribed to this calendar on your phone or in a
              calendar app, you will need to remove it there as well.
            </AlertDescription>
          </Alert>

          <AlertDialogFooter>
            <AlertDialogCancel disabled={deletingId === deleteTarget?.id}>
              Cancel
            </AlertDialogCancel>
            <AlertDialogAction
              onClick={(event) => {
                event.preventDefault();
                handleConfirmDelete();
              }}
              disabled={deletingId === deleteTarget?.id}
              aria-busy={deletingId === deleteTarget?.id}
              className={cn(buttonVariants({ variant: "destructive" }))}
            >
              {deletingId === deleteTarget?.id ? (
                <Loader2 className="size-4 animate-spin" aria-hidden />
              ) : (
                <Trash2 className="size-4" aria-hidden />
              )}
              {deletingId === deleteTarget?.id ? "Deleting…" : "Delete calendar"}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

function CalendarRow({
  sub,
  isCopied,
  isDeleting,
  onCopy,
  onDeleteClick,
}: {
  sub: CalendarSubscription;
  isCopied: boolean;
  isDeleting: boolean;
  onCopy: (sub: CalendarSubscription) => void;
  onDeleteClick: () => void;
}) {
  const filterTags = buildFilterTags(sub.filters);

  return (
    <div className="grid grid-cols-[1.4fr_1fr_1.6fr_auto] items-center gap-4 px-4 py-3.5 hover:bg-muted/60 transition-colors">
      {/* Name */}
      <div className="flex items-center gap-2.5 min-w-0">
        <div
          className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md"
          style={{ backgroundColor: `hsl(var(--primary) / 0.07)` }}
        >
          <CalendarDays className="h-3.5 w-3.5" style={{ color: PRIMARY_COLOR }} />
        </div>
        <span className="truncate text-sm font-semibold text-foreground">
          {sub.name}
        </span>
      </div>

      {/* Filters */}
      <div className="flex flex-wrap gap-1.5 min-w-0">
        {filterTags.length > 0 ? (
          filterTags.map((tag, i) => (
            <span
              key={i}
              className="inline-flex items-center rounded-md px-2 py-0.5 text-[10px] font-semibold"
              style={{
                backgroundColor: `hsl(var(--primary) / 0.07)`,
                color: PRIMARY_COLOR,
              }}
            >
              {tag}
            </span>
          ))
        ) : (
          <span className="text-xs text-muted-foreground italic">All data</span>
        )}
      </div>

      {/* URL */}
      <div className="flex items-center gap-1.5 min-w-0">
        <Link className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
        <code className="truncate rounded bg-muted px-2 py-0.5 text-[11px] text-muted-foreground font-mono">
          {sub.https_url}
        </code>
      </div>

      {/* Actions */}
      <div className="flex items-center gap-1.5 shrink-0">
        <button
          onClick={() => onCopy(sub)}
          title="Copy URL"
          className="inline-flex items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-semibold transition-all"
          style={
            isCopied
              ? {
                  borderColor: PRIMARY_COLOR,
                  backgroundColor: `hsl(var(--primary) / 0.07)`,
                  color: PRIMARY_COLOR,
                }
              : {
                  borderColor: "#e2e8f0",
                  backgroundColor: "white",
                  color: "#475569",
                }
          }
          onMouseEnter={(e) => {
            if (!isCopied) {
              e.currentTarget.style.borderColor = `hsl(var(--primary) / 0.4)`;
              e.currentTarget.style.backgroundColor = `hsl(var(--primary) / 0.03)`;
            }
          }}
          onMouseLeave={(e) => {
            if (!isCopied) {
              e.currentTarget.style.borderColor = "#e2e8f0";
              e.currentTarget.style.backgroundColor = "white";
            }
          }}
        >
          {isCopied ? (
            <Check className="h-3.5 w-3.5" />
          ) : (
            <Copy className="h-3.5 w-3.5" />
          )}
          {isCopied ? "Copied!" : "Copy URL"}
        </button>

        <button
          onClick={onDeleteClick}
          disabled={isDeleting}
          title="Delete"
          className="inline-flex h-7 w-7 items-center justify-center rounded-lg border border-transparent text-muted-foreground hover:border-red-200 hover:bg-red-50 hover:text-red-500 transition-colors disabled:opacity-50"
        >
          {isDeleting ? (
            <Loader2 className="h-3.5 w-3.5 animate-spin" />
          ) : (
            <Trash2 className="h-3.5 w-3.5" />
          )}
        </button>
      </div>
    </div>
  );
}

function buildFilterTags(filters: CalendarSubscription["filters"]): string[] {
  const tags: string[] = [];
  if (filters.bank_ids?.length) {
    tags.push(
      filters.bank_ids.length === 1
        ? "1 bank"
        : `${filters.bank_ids.length} banks`
    );
  }
  if (filters.asset_class) tags.push(filters.asset_class);
  if (filters.date_from) tags.push(`From ${filters.date_from}`);
  if (filters.date_to) tags.push(`To ${filters.date_to}`);
  return tags;
}