"use client";

import { useState, useMemo } from "react";
import { motion } from "framer-motion";
import { Button } from "@/components/atoms/button";
import { motionVariants } from "@/components/atoms";
import { ViewToggle, type ViewMode } from "@/components/atoms/view-toggle";
import { MetricCard, MetricCardSkeleton } from "@/components/molecules/MetricCard";
import { ErrorBoundary } from "@/components/molecules";
import { PageLayout } from "@/components/templates/PageLayout";
import { SearchFilterBar } from "@/components/molecules/SearchFilterBar/SearchFilterBar";
import { SubscriptionTableSkeleton } from "@/components/atoms/loading-skeleton";
import { AsyncBlock } from "@/components/molecules/AsyncBlock/AsyncBlock";
import { SubscriptionTable } from "@/features/subscriptions/components/SubscriptionTable";
import {
  SubscriptionGridCard,
  SubscriptionGridCardSkeleton,
} from "@/features/subscriptions/components/SubscriptionGridCard";
import { Server, CheckCircle, XCircle, TrendingUp } from "lucide-react";
import { useSubscriptions, useSubscriptionStats } from "@/features/subscriptions/hooks";
import {
  SUBSCRIPTION_STATUS,
  type Subscription,
  type SubscriptionStatus,
} from "@customer-portal/domain/subscriptions";

const gridContainerVariants = motionVariants.staggerContainer(0.03);
const gridItemVariants = motionVariants.fadeUpSmall;

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

function SubscriptionMetrics({
  stats,
}: {
  stats: { active: number; completed: number; cancelled: number };
}) {
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
      <MetricCard
        icon={<CheckCircle className="h-5 w-5" />}
        label="Active"
        value={stats.active}
        tone="success"
      />
      <MetricCard
        icon={<Server className="h-5 w-5" />}
        label="Total"
        value={stats.active + stats.completed + stats.cancelled}
        tone="primary"
      />
      <MetricCard
        icon={<TrendingUp className="h-5 w-5" />}
        label="Completed"
        value={stats.completed}
        tone="info"
      />
      <MetricCard
        icon={<XCircle className="h-5 w-5" />}
        label="Cancelled"
        value={stats.cancelled}
        tone="neutral"
      />
    </div>
  );
}

function SubscriptionMetricsSkeleton() {
  return (
    <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 mb-6">
      {Array.from({ length: 4 }).map((_, i) => (
        <MetricCardSkeleton key={i} />
      ))}
    </div>
  );
}

function SubscriptionGrid({
  subscriptions,
  loading,
}: {
  subscriptions: Subscription[];
  loading: boolean;
}) {
  if (subscriptions.length === 0 && !loading) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <Server className="h-10 w-10 text-muted-foreground/30 mb-3" />
        <p className="text-sm font-medium text-foreground">No subscriptions found</p>
        <p className="text-xs text-muted-foreground mt-1">No active subscriptions at this time</p>
      </div>
    );
  }

  return (
    <motion.div
      className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3"
      initial="hidden"
      animate="visible"
      variants={gridContainerVariants}
    >
      {subscriptions.map(sub => (
        <motion.div key={sub.serviceId} variants={gridItemVariants}>
          <SubscriptionGridCard subscription={sub} />
        </motion.div>
      ))}
      {loading &&
        Array.from({ length: 3 }).map((_, i) => <SubscriptionGridCardSkeleton key={`skel-${i}`} />)}
    </motion.div>
  );
}

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

  const {
    data: subscriptionData,
    error,
    isFetching,
  } = useSubscriptions(statusFilter === "all" ? {} : { status: statusFilter });
  const { data: stats } = useSubscriptionStats();
  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(
      s =>
        s.productName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        s.serviceId.toString().includes(searchTerm)
    );
  }, [subscriptions, searchTerm]);

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

  const activeFilters = useMemo(() => {
    const filters: { label: string; onRemove: () => void }[] = [];
    if (statusFilter !== "all") {
      filters.push({ label: `Status: ${statusFilter}`, onRemove: () => setStatusFilter("all") });
    }
    if (searchTerm) {
      filters.push({ label: `Search: ${searchTerm}`, onRemove: () => setSearchTerm("") });
    }
    return filters;
  }, [statusFilter, searchTerm]);

  if (showLoading || error) {
    return (
      <PageLayout icon={<Server />} title="Subscriptions">
        <AsyncBlock isLoading={false} error={error}>
          <div className="space-y-6">
            <SubscriptionMetricsSkeleton />
            <SubscriptionTableSkeleton rows={6} />
          </div>
        </AsyncBlock>
      </PageLayout>
    );
  }

  return (
    <PageLayout
      icon={<Server />}
      title="Subscriptions"
      actions={
        <Button as="a" href="/account/services" size="sm">
          Browse Services
        </Button>
      }
    >
      <ErrorBoundary>
        {stats && <SubscriptionMetrics stats={stats} />}

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

          <div className="p-4 sm:p-5">
            {viewMode === "grid" ? (
              <SubscriptionGrid
                subscriptions={filteredSubscriptions}
                loading={isFetching && !!subscriptionData}
              />
            ) : (
              <SubscriptionTable
                subscriptions={filteredSubscriptions}
                loading={isFetching && !!subscriptionData}
                className="border-0 rounded-none shadow-none"
              />
            )}
          </div>
        </div>
      </ErrorBoundary>
    </PageLayout>
  );
}

export default SubscriptionsListContainer;
