"use client";

import { useState, useMemo } from "react";
import { Button } from "@/components/atoms/button";
import { ErrorBoundary } from "@/components/molecules";
import { PageLayout } from "@/components/templates/PageLayout";
import { SubCard } from "@/components/molecules/SubCard/SubCard";
import { SearchFilterBar } from "@/components/molecules/SearchFilterBar/SearchFilterBar";
import { LoadingTable } from "@/components/atoms/loading-skeleton";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { SubscriptionTable } from "@/features/subscriptions/components/SubscriptionTable";
import { ServerIcon, CheckCircleIcon, XCircleIcon } from "@heroicons/react/24/outline";
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,
    isLoading,
    error,
  } = useSubscriptions({ status: statusFilter === "all" ? undefined : statusFilter });
  const { data: stats } = useSubscriptionStats();

  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,
      })),
    ],
    []
  );

  if (isLoading || error) {
    return (
      <PageLayout
        icon={<ServerIcon />}
        title="Subscriptions"
        description="Manage your active services and subscriptions"
      >
        <AsyncBlock isLoading={false} error={error}>
          <div className="space-y-6">
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
              {Array.from({ length: 3 }).map((_, i) => (
                <SubCard key={i}>
                  <div className="flex items-center">
                    <div className="flex-shrink-0">
                      <ServerIcon className="h-8 w-8 text-gray-300" />
                    </div>
                    <div className="ml-5 w-0 flex-1 space-y-2">
                      <div className="h-4 w-24 bg-gray-200 rounded" />
                      <div className="h-5 w-12 bg-gray-200 rounded" />
                    </div>
                  </div>
                </SubCard>
              ))}
            </div>
            <LoadingTable rows={6} columns={4} />
          </div>
        </AsyncBlock>
      </PageLayout>
    );
  }

  return (
    <PageLayout
      icon={<ServerIcon />}
      title="Subscriptions"
      description="Manage your active services and subscriptions"
      actions={
        <Button as="a" href="/catalog" size="sm">
          Order Services
        </Button>
      }
    >
      <ErrorBoundary>
        {stats && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
            <SubCard>
              <div className="flex items-center">
                <div className="flex-shrink-0">
                  <CheckCircleIcon className="h-8 w-8 text-green-600" />
                </div>
                <div className="ml-5 w-0 flex-1">
                  <dl>
                    <dt className="text-sm font-medium text-gray-500 truncate">Active</dt>
                    <dd className="text-lg font-medium text-gray-900">{stats.active}</dd>
                  </dl>
                </div>
              </div>
            </SubCard>
            <SubCard>
              <div className="flex items-center">
                <div className="flex-shrink-0">
                  <CheckCircleIcon className="h-8 w-8 text-blue-600" />
                </div>
                <div className="ml-5 w-0 flex-1">
                  <dl>
                    <dt className="text-sm font-medium text-gray-500 truncate">Completed</dt>
                    <dd className="text-lg font-medium text-gray-900">{stats.completed}</dd>
                  </dl>
                </div>
              </div>
            </SubCard>
            <SubCard>
              <div className="flex items-center">
                <div className="flex-shrink-0">
                  <XCircleIcon className="h-8 w-8 text-gray-600" />
                </div>
                <div className="ml-5 w-0 flex-1">
                  <dl>
                    <dt className="text-sm font-medium text-gray-500 truncate">Cancelled</dt>
                    <dd className="text-lg font-medium text-gray-900">{stats.cancelled}</dd>
                  </dl>
                </div>
              </div>
            </SubCard>
          </div>
        )}

        <div className="space-y-4">
          {/* Search/Filter Header */}
          <div className="bg-white/80 backdrop-blur-sm rounded-xl border border-gray-200/60 px-5 py-4 shadow-sm">
            <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 */}
          <div className="bg-white rounded-xl border border-gray-200/60 shadow-sm overflow-hidden">
            <SubscriptionTable
              subscriptions={filteredSubscriptions}
              loading={isLoading}
              className="border-0 rounded-none shadow-none"
            />
          </div>
        </div>
      </ErrorBoundary>
    </PageLayout>
  );
}

export default SubscriptionsListContainer;
