"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import type { Activity, DashboardSummary } from "@customer-portal/domain";
import {
  ServerIcon,
  ChatBubbleLeftRightIcon,
  ChevronRightIcon,
  DocumentTextIcon,
  ArrowTrendingUpIcon,
  CalendarDaysIcon,
} from "@heroicons/react/24/outline";
import {
  CreditCardIcon as CreditCardIconSolid,
  ServerIcon as ServerIconSolid,
  ChatBubbleLeftRightIcon as ChatBubbleLeftRightIconSolid,
  ClipboardDocumentListIcon as ClipboardDocumentListIconSolid,
} from "@heroicons/react/24/solid";
import { format, formatDistanceToNow } from "date-fns";

import { useAuthStore } from "@/features/auth/services/auth.store";
import { useDashboardSummary } from "@/features/dashboard/hooks";
import { StatCard, QuickAction, DashboardActivityItem } from "@/features/dashboard/components";
import { LoadingStats, LoadingTable } from "@/components/atoms";
import { ErrorState } from "@/components/atoms/error-state";
import { formatCurrency, getCurrencyLocale } from "@customer-portal/domain";
import { log } from "@customer-portal/logging";
import { useCreateInvoiceSsoLink } from "@/features/billing/hooks/useBilling";

export function DashboardView() {
  const router = useRouter();
  const { user, isAuthenticated, loading: authLoading } = useAuthStore();
  const { data: summary, isLoading: summaryLoading, error } = useDashboardSummary();
  const upcomingInvoice = summary?.nextInvoice ?? null;
  const createSsoLinkMutation = useCreateInvoiceSsoLink();

  const [paymentLoading, setPaymentLoading] = useState(false);
  const [paymentError, setPaymentError] = useState<string | null>(null);

  // Handle Pay Now functionality
  const handlePayNow = (invoiceId: number) => {
    setPaymentLoading(true);
    setPaymentError(null);

    void (async () => {
      try {
        const ssoLink = await createSsoLinkMutation.mutateAsync({ invoiceId, target: "pay" });
        window.open(ssoLink.url, "_blank", "noopener,noreferrer");
      } catch (error) {
        log.error("Failed to create payment link", { 
          invoiceId, 
          error: error instanceof Error ? error.message : String(error) 
        });
        setPaymentError(error instanceof Error ? error.message : "Failed to open payment page");
      } finally {
        setPaymentLoading(false);
      }
    })();
  };

  // Handle activity item clicks
  const handleActivityClick = (activity: Activity) => {
    if (activity.type === "invoice_created" || activity.type === "invoice_paid") {
      // Use the related invoice ID for navigation
      if (activity.relatedId) {
        router.push(`/billing/invoices/${activity.relatedId}`);
      }
    }
  };

  if (authLoading || summaryLoading || !isAuthenticated) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center space-y-4">
          <div className="space-y-6">
            <LoadingStats />
            <LoadingTable />
          </div>
          <p className="text-muted-foreground">Loading dashboard...</p>
        </div>
      </div>
    );
  }

  // Handle error state
  if (error) {
    return (
      <ErrorState
        title="Error loading dashboard"
        message={error instanceof Error ? error.message : "An unexpected error occurred"}
        variant="page"
      />
    );
  }

  return (
    <>
      <div className="min-h-screen bg-gradient-to-br from-slate-50 to-blue-50">
        <div className="max-w-[var(--cp-page-max-width)] mx-auto px-[var(--cp-page-padding)] sm:px-6 lg:px-8 py-[var(--cp-space-2xl)]">
          {/* Modern Header */}
          <div className="mb-[var(--cp-space-3xl)]">
            <div className="flex items-start justify-between gap-[var(--cp-space-xl)]">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-3 flex-wrap">
                  <h1 className="text-3xl font-bold leading-tight text-gray-900">
                    Welcome back, {user?.firstName || user?.email?.split("@")[0] || "User"}!
                  </h1>
                  {/* Tasks chip */}
                  <TasksChip summaryLoading={summaryLoading} summary={summary} />
                </div>
                <div className="mt-1 text-sm text-gray-500">Portal / Dashboard</div>
              </div>
              {/* No duplicate page-level CTAs here per guidelines */}
            </div>
          </div>

          {/* Modern Stats Grid */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-[var(--cp-space-2xl)] mb-[var(--cp-space-3xl)]">
            <StatCard
              title="Recent Orders"
              value={summary?.stats?.recentOrders ?? 0}
              icon={ClipboardDocumentListIconSolid}
              gradient="from-gray-500 to-gray-600"
              href="/orders"
            />
            <StatCard
              title="Pending Invoices"
              value={summary?.stats?.unpaidInvoices || 0}
              icon={CreditCardIconSolid}
              gradient={
                (summary?.stats?.unpaidInvoices ?? 0) > 0
                  ? "from-amber-500 to-orange-500"
                  : "from-gray-500 to-gray-600"
              }
              href="/billing/invoices"
              zeroHint={{ text: "Set up auto-pay", href: "/billing/payments" }}
            />
            <StatCard
              title="Active Services"
              value={summary?.stats?.activeSubscriptions || 0}
              icon={ServerIconSolid}
              gradient="from-blue-500 to-cyan-500"
              href="/subscriptions"
            />
            <StatCard
              title="Support Cases"
              value={summary?.stats?.openCases || 0}
              icon={ChatBubbleLeftRightIconSolid}
              gradient={
                (summary?.stats?.openCases ?? 0) > 0
                  ? "from-blue-500 to-cyan-500"
                  : "from-gray-500 to-gray-600"
              }
              href="/support/cases"
              zeroHint={{ text: "Open a ticket", href: "/support/new" }}
            />
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-3 gap-[var(--cp-space-3xl)]">
            {/* Main Content Area */}
            <div className="lg:col-span-2 space-y-[var(--cp-space-3xl)]">
              {/* Upcoming Payment - compressed attention banner */}
              {upcomingInvoice && (
                <div
                  id="attention"
                  className="bg-white rounded-xl border border-orange-200 shadow-sm p-4"
                >
                  <div className="flex items-center gap-4">
                    <div className="flex-shrink-0">
                      <div className="w-10 h-10 rounded-md bg-gradient-to-r from-amber-500 to-orange-500 flex items-center justify-center">
                        <CalendarDaysIcon className="h-5 w-5 text-white" />
                      </div>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex flex-wrap items-center gap-2 text-sm text-gray-700">
                        <span className="font-semibold text-gray-900">Upcoming Payment</span>
                        <span className="text-gray-400">•</span>
                        <span>Invoice #{upcomingInvoice.id}</span>
                        <span className="text-gray-400">•</span>
                        <span title={format(new Date(upcomingInvoice.dueDate), "MMMM d, yyyy")}>
                          Due{" "}
                          {formatDistanceToNow(new Date(upcomingInvoice.dueDate), {
                            addSuffix: true,
                          })}
                        </span>
                      </div>
                      <div className="mt-1 text-2xl font-bold text-gray-900">
                        {formatCurrency(upcomingInvoice.amount, {
                          currency: upcomingInvoice.currency || "JPY",
                          locale: getCurrencyLocale(upcomingInvoice.currency || "JPY"),
                        })}
                      </div>
                      <div className="mt-1 text-xs text-gray-500">
                        Exact due date: {format(new Date(upcomingInvoice.dueDate), "MMMM d, yyyy")}
                      </div>
                    </div>
                    <div className="flex flex-col items-end gap-2">
                      <button
                        onClick={() => handlePayNow(upcomingInvoice.id)}
                        disabled={paymentLoading}
                        className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
                      >
                        {paymentLoading ? (
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                        ) : null}
                        {paymentLoading ? "Opening Payment..." : "Pay Now"}
                        {!paymentLoading && <ChevronRightIcon className="ml-2 h-4 w-4" />}
                      </button>
                      <Link
                        href={`/billing/invoices/${upcomingInvoice.id}`}
                        className="text-blue-600 hover:text-blue-700 font-medium text-sm"
                      >
                        View invoice
                      </Link>
                    </div>
                  </div>
                </div>
              )}

              {/* Payment Error Display */}
              {paymentError && (
                <ErrorState
                  title="Payment Error"
                  message={paymentError}
                  variant="inline"
                  onRetry={() => setPaymentError(null)}
                  retryLabel="Dismiss"
                />
              )}

              {/* Recent Activity - filtered list */}
              <RecentActivityCard
                activities={summary?.recentActivity || []}
                onItemClick={handleActivityClick}
              />
            </div>

            {/* Sidebar */}
            <div className="space-y-[var(--cp-space-2xl)]">
              {/* Quick Actions - simplified */}
              <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
                <div className="px-6 py-4 border-b border-gray-100">
                  <h3 className="text-lg font-semibold text-gray-900">Quick Actions</h3>
                </div>
                <div className="p-[var(--cp-space-2xl)] space-y-[var(--cp-space-lg)]">
                  <QuickAction
                    href="/billing/invoices"
                    title="View invoices"
                    description="Review and pay invoices"
                    icon={DocumentTextIcon}
                    iconColor="text-blue-600"
                    bgColor="bg-blue-50"
                  />
                  <QuickAction
                    href="/subscriptions"
                    title="Manage services"
                    description="View active subscriptions"
                    icon={ServerIcon}
                    iconColor="text-blue-600"
                    bgColor="bg-blue-50"
                  />
                  <QuickAction
                    href="/support/new"
                    title="Get support"
                    description="Open a support ticket"
                    icon={ChatBubbleLeftRightIcon}
                    iconColor="text-blue-600"
                    bgColor="bg-blue-50"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// Helpers and small components (local to dashboard)
function TasksChip({
  summaryLoading,
  summary,
}: {
  summaryLoading: boolean;
  summary: DashboardSummary | undefined;
}) {
  const router = useRouter();
  if (summaryLoading) return null;
  const tasks: Array<{ label: string; href: string }> = [];
  if (summary?.nextInvoice) tasks.push({ label: "Pay upcoming invoice", href: "#attention" });
  const count = tasks.length;
  if (count === 0) return null;
  return (
    <button
      onClick={() => {
        const first = tasks[0];
        if (first.href.startsWith("#")) {
          const el = document.querySelector(first.href);
          if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
        } else {
          router.push(first.href);
        }
      }}
      className="inline-flex items-center rounded-full bg-blue-50 text-blue-700 px-2.5 py-1 text-xs font-medium hover:bg-blue-100"
      title={tasks.map(t => t.label).join(" • ")}
    >
      {count} tasks
    </button>
  );
}

function RecentActivityCard({
  activities,
  onItemClick,
}: {
  activities: Activity[];
  onItemClick: (a: Activity) => void;
}) {
  const [filter, setFilter] = useState<"all" | "billing" | "orders" | "support">("all");
  const filtered = activities.filter(a => {
    if (filter === "all") return true;
    if (filter === "billing") return a.type === "invoice_created" || a.type === "invoice_paid";
    if (filter === "orders") return a.type === "service_activated";
    if (filter === "support") return a.type === "case_created" || a.type === "case_closed";
    return true;
  });
  return (
    <div className="bg-white rounded-2xl shadow-lg border border-gray-100 overflow-hidden">
      <div className="px-6 py-4 border-b border-gray-100">
        <div className="flex items-center justify-between">
          <h3 className="text-lg font-semibold text-gray-900">Recent Activity</h3>
          <div className="flex items-center space-x-1 bg-gray-100 rounded-lg p-1">
            {(
              [
                { k: "all", label: "All" },
                { k: "billing", label: "Billing" },
                { k: "orders", label: "Orders" },
                { k: "support", label: "Support" },
              ] as const
            ).map(opt => (
              <button
                key={opt.k}
                onClick={() => setFilter(opt.k)}
                className={`px-2.5 py-1 text-xs rounded-md font-medium ${
                  filter === opt.k
                    ? "bg-white text-gray-900 shadow"
                    : "text-gray-600 hover:text-gray-900"
                }`}
              >
                {opt.label}
              </button>
            ))}
          </div>
        </div>
      </div>
      <div className="p-6 max-h-[360px] overflow-y-auto">
        {filtered.length > 0 ? (
          <div className="space-y-4">
            {filtered.slice(0, 10).map(activity => {
              const isClickable =
                activity.type === "invoice_created" || activity.type === "invoice_paid";
              return (
                <DashboardActivityItem
                  key={activity.id}
                  id={activity.id}
                  type={activity.type}
                  title={activity.title ?? ""}
                  description={activity.description ?? ""}
                  date={format(new Date(activity.date), "MMM d, yyyy · h:mm a")}
                  onClick={isClickable ? () => onItemClick(activity) : undefined}
                />
              );
            })}
          </div>
        ) : (
          <div className="text-center py-12">
            <ArrowTrendingUpIcon className="mx-auto h-12 w-12 text-gray-400" />
            <h3 className="mt-2 text-sm font-medium text-gray-900">No recent activity</h3>
            <p className="mt-1 text-sm text-gray-500">Your account activity will appear here.</p>
          </div>
        )}
      </div>
    </div>
  );
}
