"use client";

import { useCallback, useMemo } from "react";
import { useRouter } from "next/navigation";
import { format } from "date-fns";
import {
  ServerIcon,
  CheckCircleIcon,
  ClockIcon,
  XCircleIcon,
  CalendarIcon,
} from "@heroicons/react/24/outline";
import { DataTable } from "@/components/molecules/DataTable/DataTable";
import { StatusPill } from "@/components/atoms/status-pill";
import {
  SUBSCRIPTION_STATUS,
  SUBSCRIPTION_CYCLE,
  type Subscription,
} from "@customer-portal/domain/subscriptions";
import { Formatting } from "@customer-portal/domain/toolkit";
import { cn } from "@/lib/utils";

const { formatCurrency } = Formatting;

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

const getStatusIcon = (status: string) => {
  switch (status) {
    case SUBSCRIPTION_STATUS.ACTIVE:
      return <CheckCircleIcon className="h-5 w-5 text-green-500" />;
    case SUBSCRIPTION_STATUS.COMPLETED:
      return <CheckCircleIcon className="h-5 w-5 text-blue-500" />;
    case SUBSCRIPTION_STATUS.CANCELLED:
      return <XCircleIcon className="h-5 w-5 text-gray-500" />;
    default:
      return <ClockIcon className="h-5 w-5 text-gray-500" />;
  }
};

const getStatusVariant = (status: string) => {
  switch (status) {
    case SUBSCRIPTION_STATUS.ACTIVE:
      return "success" as const;
    case SUBSCRIPTION_STATUS.COMPLETED:
      return "info" as const;
    case SUBSCRIPTION_STATUS.CANCELLED:
      return "neutral" as const;
    default:
      return "neutral" as const;
  }
};

// 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();
  }
};

const formatDate = (dateString: string | undefined) => {
  if (!dateString) return "N/A";
  try {
    return format(new Date(dateString), "MMM d, yyyy");
  } catch {
    return "N/A";
  }
};

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

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

  const columns = useMemo(() => {
    return [
      {
        key: "service",
        header: "Service",
        className: "",
        render: (subscription: Subscription) => {
          const statusIcon = getStatusIcon(subscription.status);
          return (
            <div className="flex items-center space-x-3 py-4">
              <div className="flex-shrink-0">{statusIcon}</div>
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2.5">
                  <div className="font-semibold text-gray-900 text-sm">
                    {subscription.productName}
                  </div>
                  <StatusPill
                    label={subscription.status}
                    variant={getStatusVariant(subscription.status)}
                    size="sm"
                  />
                </div>
              </div>
            </div>
          );
        },
      },
      {
        key: "amount",
        header: "Amount",
        className: "",
        render: (subscription: Subscription) => (
          <div className="py-4 text-right">
            <div className="font-semibold text-gray-900 text-sm">
              {formatCurrency(subscription.amount, subscription.currency)}{" "}
              <span className="text-xs text-gray-500 font-normal">
                {getBillingPeriodText(subscription.cycle)}
              </span>
            </div>
          </div>
        ),
      },
      {
        key: "nextDue",
        header: "Next Due",
        className: "",
        render: (subscription: Subscription) => (
          <div className="py-4">
            <div className="flex items-center gap-2">
              <CalendarIcon className="h-4 w-4 text-gray-400" />
              <div className="text-sm font-medium text-gray-700">
                {formatDate(subscription.nextDue)}
              </div>
            </div>
          </div>
        ),
      },
    ];
  }, []);

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

  if (loading) {
    return (
      <div className={cn("bg-white overflow-hidden", className)}>
        <div className="animate-pulse">
          {/* Header skeleton */}
          <div className="bg-gradient-to-r from-gray-50 to-gray-50/80 px-6 py-4 border-b border-gray-200/80">
            <div className="grid grid-cols-3 gap-6">
              <div className="h-3 bg-gray-200 rounded w-24"></div>
              <div className="h-3 bg-gray-200 rounded w-20 ml-auto"></div>
              <div className="h-3 bg-gray-200 rounded w-24"></div>
            </div>
          </div>
          {/* Row skeletons */}
          <div className="divide-y divide-gray-100/60">
            {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-gray-200 rounded-full flex-shrink-0"></div>
                    <div className="space-y-2 flex-1">
                      <div className="h-4 bg-gray-200 rounded w-48"></div>
                    </div>
                  </div>
                  <div className="text-right">
                    <div className="h-4 bg-gray-200 rounded w-32 ml-auto"></div>
                  </div>
                  <div className="flex items-center gap-2">
                    <div className="h-4 w-4 bg-gray-200 rounded"></div>
                    <div className="h-4 bg-gray-200 rounded w-28"></div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={cn("bg-white overflow-hidden", className)}>
      <DataTable
        data={subscriptions}
        columns={columns}
        emptyState={emptyState}
        onRowClick={handleSubscriptionClick}
        className={cn(
          "subscription-table",
          // Header styling - cleaner and more modern
          "[&_thead]:bg-gradient-to-r [&_thead]:from-gray-50 [&_thead]:to-gray-50/80",
          "[&_thead_th]:px-6 [&_thead_th]:py-3.5 [&_thead_th]:text-xs [&_thead_th]:font-medium [&_thead_th]:text-gray-600 [&_thead_th]:uppercase [&_thead_th]:tracking-wide",
          "[&_thead_th]:border-b [&_thead_th]:border-gray-200/80",
          // Right-align Amount column header (2nd column)
          "[&_thead_th:nth-child(2)]:text-right",
          // Row styling - enhanced hover and spacing
          "[&_tbody_tr]:border-b [&_tbody_tr]:border-gray-100/60 [&_tbody_tr]:transition-all [&_tbody_tr]:duration-200",
          "[&_tbody_tr:hover]:bg-gradient-to-r [&_tbody_tr:hover]:from-blue-50/30 [&_tbody_tr:hover]:to-indigo-50/20 [&_tbody_tr]:cursor-pointer",
          "[&_tbody_tr:last-child]:border-b-0",
          // Cell styling - better spacing
          "[&_tbody_td]:px-6 [&_tbody_td]:py-1 [&_tbody_td]:align-top",
          // Remove default DataTable styling
          "[&_.divide-y]:divide-transparent"
        )}
      />
    </div>
  );
}

export type { SubscriptionTableProps };
