"use client";

import { useState, useEffect, useCallback } from "react";
import {
  PieChart,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  RefreshCw,
  Users,
  Building2,
  Globe,
  Briefcase,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface UnitEconomics {
  logoChurnRate: number;
  seatChurnRate: number;
  expansion: number;
  contraction: number;
  netExpansion: number;
  acvByCountry: Record<string, number>;
  acvByVertical: Record<string, number>;
  acvBySize: Record<string, number>;
  meta: {
    currency: string;
    period: string;
    calculatedAt: string;
    totalAccounts: number;
    totalSeats: number;
    activeSubscriptions: number;
  };
}

type SegmentView = "country" | "vertical" | "size";

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

// Churn indicator component
function ChurnIndicator({
  label,
  value,
  threshold,
}: {
  label: string;
  value: number;
  threshold: number;
}) {
  const isDanger = value > threshold;
  const isWarning = value > threshold * 0.7;

  return (
    <div className="flex items-center justify-between p-3 rounded-lg bg-gray-50">
      <div className="flex items-center gap-2">
        {isDanger ? (
          <AlertTriangle className="h-4 w-4 text-red-500" />
        ) : isWarning ? (
          <AlertTriangle className="h-4 w-4 text-amber-500" />
        ) : (
          <TrendingDown className="h-4 w-4 text-gray-400" />
        )}
        <span className="text-sm text-gray-600">{label}</span>
      </div>
      <span
        className={`text-lg font-bold tabular-nums ${
          isDanger
            ? "text-red-600"
            : isWarning
              ? "text-amber-600"
              : "text-gray-900"
        }`}
      >
        {value.toFixed(1)}%
      </span>
    </div>
  );
}

// Expansion bar component
function ExpansionBar({
  expansion,
  contraction,
  currency,
}: {
  expansion: number;
  contraction: number;
  currency: string;
}) {
  const total = expansion + contraction;
  const expansionPercent = total > 0 ? (expansion / total) * 100 : 50;
  const isNetPositive = expansion > contraction;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between text-sm">
        <span className="text-gray-500">Expansion vs Contraction</span>
        <span
          className={`font-semibold ${isNetPositive ? "text-emerald-600" : "text-red-600"}`}
        >
          Net: {isNetPositive ? "+" : "-"}
          {formatCurrency(Math.abs(expansion - contraction), currency)}
        </span>
      </div>
      <div className="relative h-4 rounded-full overflow-hidden bg-gray-100">
        <div
          className="absolute left-0 top-0 h-full bg-emerald-500 transition-all duration-500"
          style={{ width: `${expansionPercent}%` }}
        />
        <div
          className="absolute right-0 top-0 h-full bg-red-400 transition-all duration-500"
          style={{ width: `${100 - expansionPercent}%` }}
        />
      </div>
      <div className="flex items-center justify-between text-xs">
        <span className="text-emerald-600">
          <TrendingUp className="inline h-3 w-3 mr-1" />
          {formatCurrency(expansion, currency)}
        </span>
        <span className="text-red-500">
          {formatCurrency(contraction, currency)}
          <TrendingDown className="inline h-3 w-3 ml-1" />
        </span>
      </div>
    </div>
  );
}

// ACV segment display
function ACVSegment({
  title,
  data,
  currency,
  icon: Icon,
}: {
  title: string;
  data: Record<string, number>;
  currency: string;
  icon: React.ComponentType<{ className?: string }>;
}) {
  const entries = Object.entries(data);
  const total = entries.reduce((sum, [, value]) => sum + value, 0);

  if (entries.length === 0) {
    return (
      <div className="text-center py-4 text-gray-400 text-sm">
        No data available
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <div className="flex items-center gap-2 mb-3">
        <Icon className="h-4 w-4 text-gray-400" />
        <span className="text-sm font-medium text-gray-700">{title}</span>
      </div>
      {entries.slice(0, 5).map(([key, value]) => {
        const percent = total > 0 ? (value / total) * 100 : 0;
        return (
          <div key={key} className="space-y-1">
            <div className="flex items-center justify-between text-xs">
              <span
                className="text-gray-600 truncate max-w-[120px]"
                title={key}
              >
                {key}
              </span>
              <span className="font-medium text-gray-900">
                {formatCurrency(value, currency)}
              </span>
            </div>
            <div className="h-1.5 rounded-full bg-gray-100 overflow-hidden">
              <div
                className="h-full bg-indigo-500 transition-all duration-300"
                style={{ width: `${percent}%` }}
              />
            </div>
          </div>
        );
      })}
      {entries.length > 5 && (
        <p className="text-xs text-gray-400 text-center mt-2">
          +{entries.length - 5} more
        </p>
      )}
    </div>
  );
}

// Loading skeleton
function UnitEconomicsCardSkeleton() {
  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 gap-4 mb-6">
        <Skeleton className="h-16 w-full rounded-lg" />
        <Skeleton className="h-16 w-full rounded-lg" />
      </div>
      <Skeleton className="h-20 w-full mb-6" />
      <div className="grid grid-cols-3 gap-4">
        <Skeleton className="h-32 w-full" />
        <Skeleton className="h-32 w-full" />
        <Skeleton className="h-32 w-full" />
      </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 unit economics
            </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 UnitEconomicsCard() {
  const [data, setData] = useState<UnitEconomics | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [segmentView, setSegmentView] = useState<SegmentView>("country");

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch("/api/staff/analytics/unit-economics");
      if (!response.ok) {
        if (response.status === 403) {
          throw new Error("Insufficient permissions to view unit economics");
        }
        throw new Error("Failed to fetch unit economics");
      }
      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 <UnitEconomicsCardSkeleton />;
  }

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

  if (!data) {
    return null;
  }

  // Threshold alerts - churn > 5% is danger
  const LOGO_CHURN_THRESHOLD = 5;
  const SEAT_CHURN_THRESHOLD = 5;

  const segmentIcons: Record<
    SegmentView,
    React.ComponentType<{ className?: string }>
  > = {
    country: Globe,
    vertical: Briefcase,
    size: Building2,
  };

  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-indigo-100 p-3">
            <PieChart className="h-6 w-6 text-indigo-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Unit Economics
            </h3>
            <p className="text-xs text-gray-500">
              {data.meta.totalAccounts} accounts | {data.meta.totalSeats} seats
            </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>

      {/* Churn rates */}
      <div className="grid grid-cols-2 gap-4 mb-6">
        <ChurnIndicator
          label="Logo Churn"
          value={data.logoChurnRate}
          threshold={LOGO_CHURN_THRESHOLD}
        />
        <ChurnIndicator
          label="Seat Churn"
          value={data.seatChurnRate}
          threshold={SEAT_CHURN_THRESHOLD}
        />
      </div>

      {/* Expansion vs Contraction */}
      <div className="mb-6">
        <ExpansionBar
          expansion={data.expansion}
          contraction={data.contraction}
          currency={data.meta.currency}
        />
      </div>

      {/* ACV Segments */}
      <div className="border-t border-gray-100 pt-4">
        <div className="flex items-center justify-between mb-4">
          <span className="text-sm font-medium text-gray-700">
            ACV Breakdown
          </span>
          <div className="flex gap-1 bg-gray-100 rounded-lg p-0.5">
            {(["country", "vertical", "size"] as SegmentView[]).map((view) => {
              const Icon = segmentIcons[view];
              return (
                <button
                  key={view}
                  onClick={() => setSegmentView(view)}
                  className={`flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-md transition-colors ${
                    segmentView === view
                      ? "bg-white text-gray-900 shadow-sm"
                      : "text-gray-500 hover:text-gray-700"
                  }`}
                >
                  <Icon className="h-3 w-3" />
                  {view.charAt(0).toUpperCase() + view.slice(1)}
                </button>
              );
            })}
          </div>
        </div>

        {/* Display selected segment */}
        <div className="min-h-[140px]">
          {segmentView === "country" && (
            <ACVSegment
              title="By Country"
              data={data.acvByCountry}
              currency={data.meta.currency}
              icon={Globe}
            />
          )}
          {segmentView === "vertical" && (
            <ACVSegment
              title="By Industry"
              data={data.acvByVertical}
              currency={data.meta.currency}
              icon={Briefcase}
            />
          )}
          {segmentView === "size" && (
            <ACVSegment
              title="By Company Size"
              data={data.acvBySize}
              currency={data.meta.currency}
              icon={Building2}
            />
          )}
        </div>
      </div>

      {/* Footer */}
      <div className="mt-4 flex items-center justify-between text-xs text-gray-500">
        <span className="flex items-center gap-1">
          <Users className="h-3 w-3" />
          {data.meta.activeSubscriptions} active subscriptions
        </span>
        <span>
          Updated: {new Date(data.meta.calculatedAt).toLocaleTimeString()}
        </span>
      </div>
    </div>
  );
}
