"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";

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-slate-400">
        <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: `${PRIMARY_COLOR}12` }}
        >
          <CalendarDays className="h-6 w-6" style={{ color: PRIMARY_COLOR }} />
        </div>
        <p className="text-sm font-semibold text-slate-700">
          No calendar subscriptions yet
        </p>
        <p className="mt-1 text-xs text-slate-400">
          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-slate-100">
          {subscriptions.map((sub) => (
            <CalendarRow
              key={sub.id}
              sub={sub}
              isCopied={copiedId === sub.id}
              isDeleting={deletingId === sub.id}
              onCopy={onCopy}
              onDeleteClick={() => setDeleteTarget(sub)}
            />
          ))}
        </div>
      </div>

      {/* Delete Confirmation Modal */}
      {deleteTarget && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4"
          onClick={() => setDeleteTarget(null)}
        >
          <div
            className="w-full max-w-sm rounded-xl border border-slate-200 bg-white shadow-2xl"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="flex items-center gap-3 border-b border-slate-100 px-5 py-4">
              <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-red-50">
                <AlertTriangle className="h-5 w-5 text-red-500" />
              </div>
              <div>
                <h3 className="text-sm font-semibold text-slate-900">
                  Delete Calendar
                </h3>
                <p className="text-xs text-slate-500">
                  This action cannot be undone
                </p>
              </div>
            </div>

            {/* Body */}
            <div className="px-5 py-4">
              <p className="text-sm text-slate-600">
                Are you sure you want to delete{" "}
                <span className="font-semibold text-slate-900">
                  {deleteTarget.name}
                </span>
                ?
              </p>
              <div className="mt-3 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2.5">
                <p className="text-xs text-amber-700 font-medium">
                  ⚠️ If you've already subscribed to this calendar in your phone or calendar app, you'll need to remove it manually from there too.
                </p>
              </div>
            </div>

            {/* Footer */}
            <div className="flex items-center justify-end gap-2 border-t border-slate-100 px-5 py-3">
              <button
                onClick={() => setDeleteTarget(null)}
                className="rounded-lg border border-slate-300 bg-white px-4 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleConfirmDelete}
                disabled={deletingId === deleteTarget.id}
                className="inline-flex items-center gap-2 rounded-lg bg-red-500 px-4 py-2 text-sm font-semibold text-white hover:bg-red-600 transition-colors disabled:opacity-50"
              >
                {deletingId === deleteTarget.id ? (
                  <Loader2 className="h-3.5 w-3.5 animate-spin" />
                ) : (
                  <Trash2 className="h-3.5 w-3.5" />
                )}
                {deletingId === deleteTarget.id ? "Deleting…" : "Yes, Delete"}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

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-slate-50/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: `${PRIMARY_COLOR}12` }}
        >
          <CalendarDays className="h-3.5 w-3.5" style={{ color: PRIMARY_COLOR }} />
        </div>
        <span className="truncate text-sm font-semibold text-slate-800">
          {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: `${PRIMARY_COLOR}12`,
                color: PRIMARY_COLOR,
              }}
            >
              {tag}
            </span>
          ))
        ) : (
          <span className="text-xs text-slate-400 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-slate-400" />
        <code className="truncate rounded bg-slate-100 px-2 py-0.5 text-[11px] text-slate-600 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: `${PRIMARY_COLOR}12`,
                  color: PRIMARY_COLOR,
                }
              : {
                  borderColor: "#e2e8f0",
                  backgroundColor: "white",
                  color: "#475569",
                }
          }
          onMouseEnter={(e) => {
            if (!isCopied) {
              e.currentTarget.style.borderColor = `${PRIMARY_COLOR}66`;
              e.currentTarget.style.backgroundColor = `${PRIMARY_COLOR}08`;
            }
          }}
          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-slate-400 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;
}