"use client";

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

interface HealthDistribution {
  healthy: number;
  atRisk: number;
  critical: number;
  total: number;
}

interface AtRiskAccount {
  tenantId: string;
  tenantName: string;
  tenantEmail: string;
  healthScore: number;
  healthStatus: "healthy" | "at_risk" | "critical";
  riskLevel: "low" | "medium" | "high" | "critical";
  tier: string | null;
  mrr: number;
}

interface CustomerHealthData {
  distribution: HealthDistribution;
  averageHealthScore: number;
  trend: number;
  atRiskAccounts: AtRiskAccount[];
  calculatedAt: string;
}

// Health status color mapping
function getStatusColor(status: string): string {
  switch (status) {
    case "healthy":
      return "text-emerald-600 bg-emerald-50";
    case "at_risk":
      return "text-amber-600 bg-amber-50";
    case "critical":
      return "text-red-600 bg-red-50";
    default:
      return "text-gray-600 bg-gray-50";
  }
}

function getRiskBadgeColor(level: string): string {
  switch (level) {
    case "low":
      return "bg-emerald-100 text-emerald-700";
    case "medium":
      return "bg-amber-100 text-amber-700";
    case "high":
      return "bg-orange-100 text-orange-700";
    case "critical":
      return "bg-red-100 text-red-700";
    default:
      return "bg-gray-100 text-gray-700";
  }
}

// Health score circle component
function HealthScoreCircle({ score }: { score: number }) {
  const circumference = 2 * Math.PI * 40;
  const strokeDashoffset = circumference - (score / 100) * circumference;

  const getColor = () => {
    if (score >= 70) return "text-emerald-500";
    if (score >= 40) return "text-amber-500";
    return "text-red-500";
  };

  return (
    <div className="relative w-24 h-24">
      <svg className="w-24 h-24 transform -rotate-90">
        <circle
          cx="48"
          cy="48"
          r="40"
          fill="none"
          stroke="currentColor"
          strokeWidth="8"
          className="text-gray-100"
        />
        <circle
          cx="48"
          cy="48"
          r="40"
          fill="none"
          stroke="currentColor"
          strokeWidth="8"
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          className={getColor()}
        />
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span className={`text-2xl font-bold ${getColor()}`}>{score}</span>
        <span className="text-xs text-gray-500">avg</span>
      </div>
    </div>
  );
}

// Distribution bar component
function DistributionBar({
  distribution,
}: {
  distribution: HealthDistribution;
}) {
  const total = distribution.total || 1;
  const healthyPercent = (distribution.healthy / total) * 100;
  const atRiskPercent = (distribution.atRisk / total) * 100;
  const criticalPercent = (distribution.critical / total) * 100;

  return (
    <div className="space-y-2">
      <div className="flex h-3 rounded-full overflow-hidden bg-gray-100">
        <div
          className="bg-emerald-500 transition-all duration-500"
          style={{ width: `${healthyPercent}%` }}
        />
        <div
          className="bg-amber-500 transition-all duration-500"
          style={{ width: `${atRiskPercent}%` }}
        />
        <div
          className="bg-red-500 transition-all duration-500"
          style={{ width: `${criticalPercent}%` }}
        />
      </div>
      <div className="flex justify-between text-xs">
        <span className="flex items-center gap-1.5">
          <span className="h-2 w-2 rounded-full bg-emerald-500" />
          <span className="text-gray-600">
            Healthy ({distribution.healthy})
          </span>
        </span>
        <span className="flex items-center gap-1.5">
          <span className="h-2 w-2 rounded-full bg-amber-500" />
          <span className="text-gray-600">At Risk ({distribution.atRisk})</span>
        </span>
        <span className="flex items-center gap-1.5">
          <span className="h-2 w-2 rounded-full bg-red-500" />
          <span className="text-gray-600">
            Critical ({distribution.critical})
          </span>
        </span>
      </div>
    </div>
  );
}

// Loading skeleton
function CustomerHealthSkeleton() {
  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="flex items-center gap-8 mb-6">
        <Skeleton className="h-24 w-24 rounded-full" />
        <div className="flex-1">
          <Skeleton className="h-3 w-full mb-2" />
          <Skeleton className="h-4 w-3/4" />
        </div>
      </div>
      <div className="space-y-3">
        {[...Array(3)].map((_, i) => (
          <Skeleton key={i} className="h-12 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 customer health
            </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 CustomerHealthCard() {
  const [data, setData] = useState<CustomerHealthData | 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/customer-health");
      if (!response.ok) {
        throw new Error("Failed to fetch customer health data");
      }
      const result = await response.json();
      if (result.success) {
        setData(result.data);
      } else {
        throw new Error(result.error || "Unknown error");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [fetchData]);

  if (loading) return <CustomerHealthSkeleton />;
  if (error) return <ErrorState message={error} onRetry={fetchData} />;
  if (!data) return null;

  const trendUp = data.trend > 0;
  const trendNeutral = data.trend === 0;

  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-rose-100 p-3">
            <HeartPulse className="h-6 w-6 text-rose-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Customer Health
            </h3>
            <p className="text-xs text-gray-500">
              {data.distribution.total} accounts tracked
            </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>

      {/* Health Score and Distribution */}
      <div className="flex items-center gap-8 mb-6">
        <HealthScoreCircle score={data.averageHealthScore} />
        <div className="flex-1">
          <div className="flex items-center gap-2 mb-3">
            {!trendNeutral && (
              <span
                className={`flex items-center gap-1 text-sm ${trendUp ? "text-emerald-600" : "text-red-600"}`}
              >
                {trendUp ? (
                  <TrendingUp className="h-4 w-4" />
                ) : (
                  <TrendingDown className="h-4 w-4" />
                )}
                {Math.abs(data.trend)}% vs last period
              </span>
            )}
          </div>
          <DistributionBar distribution={data.distribution} />
        </div>
      </div>

      {/* At-Risk Accounts Preview */}
      {data.atRiskAccounts.length > 0 && (
        <div className="border-t border-gray-100 pt-4">
          <div className="flex items-center justify-between mb-3">
            <h4 className="text-sm font-medium text-gray-700 flex items-center gap-2">
              <AlertCircle className="h-4 w-4 text-amber-500" />
              Top At-Risk Accounts
            </h4>
            <span className="text-xs text-gray-500">
              {data.atRiskAccounts.length} accounts need attention
            </span>
          </div>
          <div className="space-y-2">
            {data.atRiskAccounts.slice(0, 5).map((account) => (
              <div
                key={account.tenantId}
                className="flex items-center justify-between p-3 rounded-lg bg-gray-50 hover:bg-gray-100 transition-colors cursor-pointer"
              >
                <div className="flex items-center gap-3">
                  <div
                    className={`h-8 w-8 rounded-full flex items-center justify-center ${getStatusColor(account.healthStatus)}`}
                  >
                    <Users className="h-4 w-4" />
                  </div>
                  <div>
                    <p className="text-sm font-medium text-gray-900">
                      {account.tenantName}
                    </p>
                    <p className="text-xs text-gray-500">
                      {account.tenantEmail}
                    </p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-sm font-bold tabular-nums text-gray-700">
                    {account.healthScore}
                  </span>
                  <span
                    className={`px-2 py-0.5 rounded-full text-xs font-medium ${getRiskBadgeColor(account.riskLevel)}`}
                  >
                    {account.riskLevel}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Footer */}
      <div className="mt-4 flex items-center justify-between text-xs text-gray-500">
        <span className="flex items-center gap-1">
          <span className="h-2 w-2 rounded-full bg-emerald-500" />
          {data.distribution.healthy} healthy
        </span>
        <span>Updated: {new Date(data.calculatedAt).toLocaleTimeString()}</span>
      </div>
    </div>
  );
}
