"use client";

import { useCallback } from "react";
import { useRouter } from "next/navigation";
import { ServerIcon, CalendarIcon } from "@heroicons/react/24/outline";
import { DataTable } from "@/components/molecules/DataTable/DataTable";
import { StatusPill } from "@/components/atoms/status-pill";
import { SUBSCRIPTION_CYCLE, type Subscription } from "@customer-portal/domain/subscriptions";
import { Formatting } from "@customer-portal/domain/toolkit";
import { cn, formatIsoDate } from "@/shared/utils";
import {
  getSubscriptionStatusIcon,
  getSubscriptionStatusVariant,
} from "@/features/subscriptions/utils/status-presenters";

const { formatCurrency } = Formatting;

interface SubscriptionTableProps {
  subscriptions: Subscription[];
  loading?: boolean;
  onSubscriptionClick?: (subscription: Subscription) => void;
  className?: string;
}

// Simple UI helper - converts cycle to display text
const getBillingPeriodText = (cycle: string): string => {
  switch (cycle) {
    case SUBSCRIPTION_CYCLE.MONTHLY:
      return "per month";
    case SUBSCRIPTION_CYCLE.ANNUALLY:
      return "per year";
    case SUBSCRIPTION_CYCLE.QUARTERLY:
      return "per quarter";
    case SUBSCRIPTION_CYCLE.SEMI_ANNUALLY:
      return "per 6 months";
    case SUBSCRIPTION_CYCLE.BIENNIALLY:
      return "per 2 years";
    case SUBSCRIPTION_CYCLE.TRIENNIALLY:
      return "per 3 years";
    case SUBSCRIPTION_CYCLE.ONE_TIME:
      return "one-time";
    case SUBSCRIPTION_CYCLE.FREE:
      return "free";
    default:
      return cycle.toLowerCase();
  }
};

function SubscriptionTableSkeleton({ className }: { className: string | undefined }) {
  return (
    <div className={cn("bg-card overflow-hidden", className)}>
      <div className="animate-pulse">
        <div className="bg-muted/50 px-6 py-4 border-b border-border">
          <div className="grid grid-cols-3 gap-6">
            <div className="h-3 bg-muted rounded w-24"></div>
            <div className="h-3 bg-muted rounded w-20 ml-auto"></div>
            <div className="h-3 bg-muted rounded w-24"></div>
          </div>
        </div>
        <div className="divide-y divide-border">
          {Array.from({ length: 6 }).map((_, i) => (
            <div key={i} className="px-6 py-5">
              <div className="grid grid-cols-3 gap-6 items-center">
                <div className="flex items-center space-x-3">
                  <div className="h-5 w-5 bg-muted rounded-full flex-shrink-0"></div>
                  <div className="space-y-2 flex-1">
                    <div className="h-4 bg-muted rounded w-48"></div>
                  </div>
                </div>
                <div className="text-right">
                  <div className="h-4 bg-muted rounded w-32 ml-auto"></div>
                </div>
                <div className="flex items-center gap-2">
                  <div className="h-4 w-4 bg-muted rounded"></div>
                  <div className="h-4 bg-muted rounded w-28"></div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

const TABLE_CLASS_NAMES = cn(
  "subscription-table",
  "[&_thead]:bg-muted/50",
  "[&_thead_th]:px-6 [&_thead_th]:py-3.5 [&_thead_th]:text-xs [&_thead_th]:font-medium [&_thead_th]:text-muted-foreground [&_thead_th]:uppercase [&_thead_th]:tracking-wide",
  "[&_thead_th]:border-b [&_thead_th]:border-border",
  "[&_thead_th:nth-child(2)]:text-right",
  "[&_tbody_tr]:border-b [&_tbody_tr]:border-border [&_tbody_tr]:transition-all [&_tbody_tr]:duration-200",
  "[&_tbody_tr:hover]:bg-primary/5 [&_tbody_tr]:cursor-pointer",
  "[&_tbody_tr:last-child]:border-b-0",
  "[&_tbody_td]:px-6 [&_tbody_td]:py-1 [&_tbody_td]:align-top",
  "[&_.divide-y]:divide-transparent"
);

const TABLE_COLUMNS = [
  {
    key: "service",
    header: "Service",
    className: "",
    render: (subscription: Subscription) => (
      <div className="flex items-center space-x-3 py-5">
        <div className="flex-shrink-0">{getSubscriptionStatusIcon(subscription.status)}</div>
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2.5">
            <div className="font-semibold text-foreground text-sm">{subscription.productName}</div>
            <StatusPill
              label={subscription.status}
              variant={getSubscriptionStatusVariant(subscription.status)}
              size="sm"
            />
          </div>
        </div>
      </div>
    ),
  },
  {
    key: "amount",
    header: "Amount",
    className: "",
    render: (subscription: Subscription) => (
      <div className="py-5 text-right">
        <div className="font-bold text-foreground text-sm tabular-nums">
          {formatCurrency(subscription.amount, subscription.currency)}{" "}
          <span className="text-xs text-muted-foreground font-normal">
            {getBillingPeriodText(subscription.cycle)}
          </span>
        </div>
      </div>
    ),
  },
  {
    key: "nextDue",
    header: "Next Due",
    className: "",
    render: (subscription: Subscription) => (
      <div className="py-5">
        <div className="flex items-center gap-2">
          <CalendarIcon className="h-4 w-4 text-muted-foreground" />
          <div className="text-sm font-medium text-foreground">
            {formatIsoDate(subscription.nextDue)}
          </div>
        </div>
      </div>
    ),
  },
];

const TABLE_EMPTY_STATE = {
  icon: <ServerIcon className="h-12 w-12" />,
  title: "No subscriptions found",
  description: "No active subscriptions at this time.",
};

export function SubscriptionTable({
  subscriptions,
  loading = false,
  onSubscriptionClick,
  className,
}: SubscriptionTableProps) {
  const router = useRouter();

  const handleSubscriptionClick = useCallback(
    (subscription: Subscription) => {
      if (onSubscriptionClick) {
        onSubscriptionClick(subscription);
      } else {
        router.push(`/account/subscriptions/${subscription.id}`);
      }
    },
    [onSubscriptionClick, router]
  );

  if (loading) return <SubscriptionTableSkeleton className={className} />;

  return (
    <div className={cn("bg-card overflow-hidden", className)}>
      <DataTable
        data={subscriptions}
        columns={TABLE_COLUMNS}
        emptyState={TABLE_EMPTY_STATE}
        onRowClick={handleSubscriptionClick}
        className={TABLE_CLASS_NAMES}
      />
    </div>
  );
}

export type { SubscriptionTableProps };
