"use client";

import { useState, useMemo } from "react";
import { Button } from "@/components/atoms/button";
import { ErrorBoundary, SummaryStats } from "@/components/molecules";
import type { StatItem } from "@/components/molecules/SummaryStats";
import { PageLayout } from "@/components/templates/PageLayout";
import { SearchFilterBar } from "@/components/molecules/SearchFilterBar/SearchFilterBar";
import {
  SubscriptionStatsCardsSkeleton,
  SubscriptionTableSkeleton,
} from "@/components/atoms/loading-skeleton";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { SubscriptionTable } from "@/features/subscriptions/components/SubscriptionTable";
import { Server, CheckCircle, XCircle } from "lucide-react";
import { useSubscriptions, useSubscriptionStats } from "@/features/subscriptions/hooks";
import {
  SUBSCRIPTION_STATUS,
  type Subscription,
  type SubscriptionStatus,
} from "@customer-portal/domain/subscriptions";

const SUBSCRIPTION_STATUS_OPTIONS = Object.values(SUBSCRIPTION_STATUS) as SubscriptionStatus[];

export function SubscriptionsListContainer() {
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<SubscriptionStatus | "all">("all");

  const {
    data: subscriptionData,
    error,
    isFetching,
  } = useSubscriptions(statusFilter === "all" ? {} : { status: statusFilter });
  const { data: stats } = useSubscriptionStats();

  // Simple loading check: show skeleton until we have data or an error
  const showLoading = !subscriptionData && !error;

  const subscriptions = useMemo((): Subscription[] => {
    if (!subscriptionData) return [];
    if (Array.isArray(subscriptionData)) return subscriptionData;
    return subscriptionData.subscriptions;
  }, [subscriptionData]);

  const filteredSubscriptions = useMemo(() => {
    if (!searchTerm) return subscriptions;
    return subscriptions.filter(subscription => {
      const matchesSearch =
        subscription.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        subscription.serviceId.toString().includes(searchTerm);
      return matchesSearch;
    });
  }, [subscriptions, searchTerm]);

  const statusFilterOptions = useMemo(
    () => [
      { value: "all" as const, label: "All Status" },
      ...SUBSCRIPTION_STATUS_OPTIONS.map(status => ({
        value: status,
        label: status,
      })),
    ],
    []
  );

  // Show skeleton when loading, error state when error
  if (showLoading || error) {
    return (
      <PageLayout
        icon={<Server />}
        title="Subscriptions"
        description="Manage your active subscriptions"
      >
        <AsyncBlock isLoading={false} error={error}>
          <div className="space-y-6">
            <SubscriptionStatsCardsSkeleton />
            <SubscriptionTableSkeleton rows={6} />
          </div>
        </AsyncBlock>
      </PageLayout>
    );
  }

  return (
    <PageLayout
      icon={<Server />}
      title="Subscriptions"
      description="Manage your active subscriptions"
      actions={
        <Button as="a" href="/account/services" size="sm">
          Browse Services
        </Button>
      }
    >
      <ErrorBoundary>
        {stats && (
          <SummaryStats
            variant="cards"
            className="mb-6"
            items={
              [
                {
                  icon: <CheckCircle className="h-5 w-5" />,
                  label: "Active",
                  value: stats.active,
                  tone: "success",
                },
                {
                  icon: <CheckCircle className="h-5 w-5" />,
                  label: "Completed",
                  value: stats.completed,
                  tone: "primary",
                },
                {
                  icon: <XCircle className="h-5 w-5" />,
                  label: "Cancelled",
                  value: stats.cancelled,
                  tone: "muted",
                },
              ] satisfies StatItem[]
            }
          />
        )}

        <div className="bg-card rounded-xl border border-border shadow-[var(--cp-shadow-1)] overflow-hidden">
          {/* Search/Filter Header */}
          <div className="px-6 py-4 border-b border-border">
            <SearchFilterBar
              searchValue={searchTerm}
              onSearchChange={setSearchTerm}
              searchPlaceholder="Search subscriptions..."
              filterValue={statusFilter}
              onFilterChange={value => setStatusFilter(value as SubscriptionStatus | "all")}
              filterOptions={statusFilterOptions}
              filterLabel="Filter by status"
            />
          </div>

          {/* Subscriptions Table */}
          <SubscriptionTable
            subscriptions={filteredSubscriptions}
            loading={isFetching && !!subscriptionData}
            className="border-0 rounded-none shadow-none"
          />
        </div>
      </ErrorBoundary>
    </PageLayout>
  );
}

export default SubscriptionsListContainer;
