"use client";

import { useState, useEffect, useCallback } from "react";
import {
  DollarSign,
  Users,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  RefreshCw,
  Banknote,
  Calendar,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface RevenueMetrics {
  revenue30Days: number;
  activeSubscriptions: number;
  churn30Days: number;
  mrr: number;
  arr: number;
  nrr: number;
  expansion: number;
  contraction: number;
  trends: {
    revenueDelta: number;
    subscriptionsDelta: number;
    churnDelta: number;
  };
  meta: {
    currency: string;
    period: string;
    calculatedAt: string;
    subscriptionBreakdown: {
      active: number;
      trialing: number;
    };
  };
}

// Format currency
function formatCurrency(value: number, currency = "GBP"): string {
  return new Intl.NumberFormat("en-GB", {
    style: "currency",
    currency,
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(value);
}

// Metric sub-card component
function MetricItem({
  label,
  value,
  change,
  icon: Icon,
  warning,
  danger,
}: {
  label: string;
  value: string | number;
  change?: number;
  icon: React.ComponentType<{ className?: string }>;
  warning?: boolean;
  danger?: boolean;
}) {
  const isPositive = change !== undefined && change >= 0;
  const colorClass = danger
    ? "text-red-600"
    : warning
      ? "text-amber-600"
      : "text-gray-900";

  return (
    <div className="relative">
      <div className="flex items-center gap-2 mb-1">
        <Icon
          className={`h-4 w-4 ${danger ? "text-red-500" : warning ? "text-amber-500" : "text-gray-400"}`}
        />
        <span className="text-xs font-medium text-gray-500">{label}</span>
      </div>
      <div className="flex items-baseline gap-2">
        <span className={`text-xl font-bold tabular-nums ${colorClass}`}>
          {value}
        </span>
        {change !== undefined && (
          <span
            className={`inline-flex items-center gap-0.5 text-xs font-semibold ${
              isPositive ? "text-emerald-600" : "text-red-600"
            }`}
          >
            {isPositive ? (
              <TrendingUp className="h-3 w-3" />
            ) : (
              <TrendingDown className="h-3 w-3" />
            )}
            {Math.abs(change)}%
          </span>
        )}
        {danger && <AlertTriangle className="h-4 w-4 text-red-500" />}
        {warning && !danger && (
          <AlertTriangle className="h-4 w-4 text-amber-500" />
        )}
      </div>
    </div>
  );
}

// Loading skeleton
function RevenueCardSkeleton() {
  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6">
      <div className="flex items-center justify-between mb-6">
        <Skeleton className="h-6 w-48" />
        <Skeleton className="h-8 w-8 rounded-full" />
      </div>
      <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
        {[...Array(4)].map((_, i) => (
          <div key={i}>
            <Skeleton className="h-4 w-20 mb-2" />
            <Skeleton className="h-8 w-24" />
          </div>
        ))}
      </div>
      <div className="mt-6 pt-4 border-t border-gray-100">
        <div className="grid grid-cols-2 gap-4">
          <Skeleton className="h-4 w-full" />
          <Skeleton className="h-4 w-full" />
        </div>
      </div>
    </div>
  );
}

// Error state component
function ErrorState({
  message,
  onRetry,
}: {
  message: string;
  onRetry: () => void;
}) {
  return (
    <div className="rounded-2xl border border-red-100 bg-red-50 p-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="rounded-full bg-red-100 p-2">
            <AlertTriangle className="h-5 w-5 text-red-600" />
          </div>
          <div>
            <p className="font-medium text-red-900">
              Failed to load revenue data
            </p>
            <p className="text-sm text-red-700">{message}</p>
          </div>
        </div>
        <button
          onClick={onRetry}
          className="flex items-center gap-2 rounded-lg bg-red-100 px-4 py-2 text-sm font-medium text-red-700 hover:bg-red-200 transition-colors"
        >
          <RefreshCw className="h-4 w-4" />
          Retry
        </button>
      </div>
    </div>
  );
}

export default function RevenueCard() {
  const [data, setData] = useState<RevenueMetrics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/staff/analytics/revenue");
      if (!response.ok) {
        if (response.status === 403) {
          throw new Error("Insufficient permissions to view revenue data");
        }
        throw new Error("Failed to fetch revenue data");
      }
      const result = await response.json();
      setData(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    // Auto-refresh every 5 minutes
    const interval = setInterval(fetchData, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [fetchData]);

  if (loading) {
    return <RevenueCardSkeleton />;
  }

  if (error) {
    return <ErrorState message={error} onRetry={fetchData} />;
  }

  if (!data) {
    return null;
  }

  // Threshold alerts
  const isChurnHigh = data.churn30Days > 5;
  const isNRRLow = data.nrr < 100;

  return (
    <div className="rounded-2xl border border-gray-100 bg-white p-6 shadow-sm hover:shadow-lg transition-shadow">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className="rounded-xl bg-emerald-100 p-3">
            <DollarSign className="h-6 w-6 text-emerald-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Revenue & Subscriptions
            </h3>
            <p className="text-xs text-gray-500">Last 30 days</p>
          </div>
        </div>
        <button
          onClick={fetchData}
          disabled={loading}
          className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors disabled:opacity-50"
          title="Refresh data"
        >
          <RefreshCw className={`h-5 w-5 ${loading ? "animate-spin" : ""}`} />
        </button>
      </div>

      {/* Main metrics grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-6">
        <MetricItem
          label="Revenue (30d)"
          value={formatCurrency(data.revenue30Days, data.meta.currency)}
          change={data.trends.revenueDelta}
          icon={Banknote}
        />
        <MetricItem
          label="Active Subscriptions"
          value={data.activeSubscriptions}
          change={data.trends.subscriptionsDelta}
          icon={Users}
        />
        <MetricItem
          label="MRR"
          value={formatCurrency(data.mrr, data.meta.currency)}
          icon={Calendar}
        />
        <MetricItem
          label="Churn (30d)"
          value={data.churn30Days}
          change={data.trends.churnDelta}
          icon={TrendingDown}
          danger={isChurnHigh}
          warning={data.churn30Days > 3}
        />
      </div>

      {/* Secondary metrics */}
      <div className="mt-6 pt-4 border-t border-gray-100">
        <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-500">ARR</span>
            <span className="text-sm font-semibold text-gray-900">
              {formatCurrency(data.arr, data.meta.currency)}
            </span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-500">NRR</span>
            <span
              className={`text-sm font-semibold ${isNRRLow ? "text-amber-600" : "text-emerald-600"}`}
            >
              {data.nrr}%
              {isNRRLow && (
                <span className="ml-1 text-xs text-amber-500">
                  (target: 100%+)
                </span>
              )}
            </span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-500">Expansion</span>
            <span className="text-sm font-semibold text-emerald-600">
              +{formatCurrency(data.expansion, data.meta.currency)}
            </span>
          </div>
          <div className="flex items-center justify-between">
            <span className="text-sm text-gray-500">Contraction</span>
            <span className="text-sm font-semibold text-red-600">
              -{formatCurrency(data.contraction, data.meta.currency)}
            </span>
          </div>
        </div>
      </div>

      {/* Subscription breakdown */}
      <div className="mt-4 flex items-center gap-4 text-xs text-gray-500">
        <span className="flex items-center gap-1">
          <span className="h-2 w-2 rounded-full bg-emerald-500" />
          Active: {data.meta.subscriptionBreakdown.active}
        </span>
        <span className="flex items-center gap-1">
          <span className="h-2 w-2 rounded-full bg-blue-500" />
          Trialing: {data.meta.subscriptionBreakdown.trialing}
        </span>
        <span className="ml-auto">
          Updated: {new Date(data.meta.calculatedAt).toLocaleTimeString()}
        </span>
      </div>
    </div>
  );
}
