"use client";

import { useState, useEffect, useCallback } from "react";
import {
  AlertTriangle,
  RefreshCw,
  TrendingDown,
  Mail,
  Calendar,
  UserPlus,
  Bell,
  BellOff,
  CreditCard,
  MessageSquare,
  Clock,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface RiskReason {
  type: string;
  severity: number;
  detail: string;
}

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

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

interface AtRiskData {
  atRiskAccounts: AtRiskAccount[];
  distribution: HealthDistribution;
  calculatedAt: string;
}

// Risk type icon mapping
function getRiskIcon(type: string) {
  switch (type) {
    case "usage_cliff_7d":
    case "usage_cliff_14d":
    case "usage_cliff_28d":
      return <TrendingDown className="h-4 w-4" />;
    case "payment_failed":
      return <CreditCard className="h-4 w-4" />;
    case "support_spike":
      return <MessageSquare className="h-4 w-4" />;
    case "no_login":
      return <Clock className="h-4 w-4" />;
    default:
      return <AlertTriangle className="h-4 w-4" />;
  }
}

// Risk reason badge color
function getReasonBadgeColor(severity: number): string {
  if (severity >= 80) return "bg-red-100 text-red-700 border-red-200";
  if (severity >= 60) return "bg-orange-100 text-orange-700 border-orange-200";
  if (severity >= 40) return "bg-amber-100 text-amber-700 border-amber-200";
  return "bg-gray-100 text-gray-700 border-gray-200";
}

// Risk level styling
function getRiskLevelStyle(level: string): string {
  switch (level) {
    case "critical":
      return "bg-red-500 text-white";
    case "high":
      return "bg-orange-500 text-white";
    case "medium":
      return "bg-amber-500 text-white";
    case "low":
      return "bg-emerald-500 text-white";
    default:
      return "bg-gray-500 text-white";
  }
}

// Playbook button component
interface PlaybookButtonProps {
  type: "recovery" | "qbr" | "csm";
  tenantId: string;
  onAction: (type: string, tenantId: string) => void;
  loading?: boolean;
}

function PlaybookButton({
  type,
  tenantId,
  onAction,
  loading,
}: PlaybookButtonProps) {
  const config = {
    recovery: {
      icon: <Mail className="h-4 w-4" />,
      label: "Recovery Sequence",
      color: "text-blue-600 hover:bg-blue-50",
    },
    qbr: {
      icon: <Calendar className="h-4 w-4" />,
      label: "Schedule QBR",
      color: "text-purple-600 hover:bg-purple-50",
    },
    csm: {
      icon: <UserPlus className="h-4 w-4" />,
      label: "Assign CSM",
      color: "text-emerald-600 hover:bg-emerald-50",
    },
  };

  const { icon, label, color } = config[type];

  return (
    <button
      onClick={() => onAction(type, tenantId)}
      disabled={loading}
      className={`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${color} disabled:opacity-50`}
    >
      {icon}
      {label}
    </button>
  );
}

// Loading skeleton
function AtRiskSkeleton() {
  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="space-y-4">
        {[...Array(4)].map((_, i) => (
          <div key={i} className="p-4 rounded-lg border border-gray-100">
            <div className="flex items-start justify-between mb-3">
              <Skeleton className="h-5 w-40" />
              <Skeleton className="h-6 w-16 rounded-full" />
            </div>
            <Skeleton className="h-4 w-full mb-2" />
            <div className="flex gap-2">
              <Skeleton className="h-8 w-32" />
              <Skeleton className="h-8 w-28" />
            </div>
          </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 at-risk accounts
            </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>
  );
}

// Snooze state tracking (in-memory for now)
const snoozedAccounts = new Set<string>();

export default function AtRiskPanel() {
  const [data, setData] = useState<AtRiskData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [snoozed, setSnoozed] = useState<Set<string>>(new Set(snoozedAccounts));

  const fetchData = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch(
        "/api/staff/analytics/customer-health?view=at-risk",
      );
      if (!response.ok) {
        throw new Error("Failed to fetch at-risk accounts");
      }
      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]);

  const handlePlaybookAction = async (actionType: string, tenantId: string) => {
    setActionLoading(`${actionType}-${tenantId}`);
    try {
      let endpoint = "";
      let body = {};

      switch (actionType) {
        case "recovery":
          endpoint = "/api/staff/playbooks/recovery-sequence";
          body = { tenantId, sequenceType: "gentle_reminder" };
          break;
        case "qbr":
          endpoint = "/api/staff/playbooks/schedule-qbr";
          body = { tenantId, suggestedDates: [], attendees: [] };
          break;
        case "csm":
          // CSM assignment - log for now, could expand to dedicated endpoint
          console.log(`CSM assignment requested for ${tenantId}`);
          return;
        default:
          console.warn(`Unknown playbook action: ${actionType}`);
          return;
      }

      const response = await fetch(endpoint, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });

      if (!response.ok) {
        throw new Error(`Failed to trigger ${actionType}`);
      }

      const result = await response.json();
      if (result.success) {
        console.log(`Triggered ${actionType} for ${tenantId}:`, result.data);
        // Optionally refresh the data after successful action
        fetchData();
      } else {
        throw new Error(result.error || "Unknown error");
      }
    } catch (err) {
      console.error("Playbook action failed:", err);
    } finally {
      setActionLoading(null);
    }
  };

  const handleSnooze = (tenantId: string) => {
    const newSnoozed = new Set(snoozed);
    if (newSnoozed.has(tenantId)) {
      newSnoozed.delete(tenantId);
      snoozedAccounts.delete(tenantId);
    } else {
      newSnoozed.add(tenantId);
      snoozedAccounts.add(tenantId);
    }
    setSnoozed(newSnoozed);
  };

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

  // Filter out snoozed accounts
  const visibleAccounts = data.atRiskAccounts.filter(
    (a) => !snoozed.has(a.tenantId),
  );
  const snoozedCount = data.atRiskAccounts.length - visibleAccounts.length;

  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-amber-100 p-3">
            <AlertTriangle className="h-6 w-6 text-amber-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              At-Risk Accounts
            </h3>
            <p className="text-xs text-gray-500">
              {visibleAccounts.length} accounts need attention
              {snoozedCount > 0 && ` (${snoozedCount} snoozed)`}
            </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>

      {/* Summary stats */}
      <div className="grid grid-cols-4 gap-4 mb-6 p-4 rounded-lg bg-gray-50">
        <div className="text-center">
          <p className="text-2xl font-bold text-red-600">
            {data.distribution.critical}
          </p>
          <p className="text-xs text-gray-500">Critical</p>
        </div>
        <div className="text-center">
          <p className="text-2xl font-bold text-orange-600">
            {visibleAccounts.filter((a) => a.riskLevel === "high").length}
          </p>
          <p className="text-xs text-gray-500">High Risk</p>
        </div>
        <div className="text-center">
          <p className="text-2xl font-bold text-amber-600">
            {visibleAccounts.filter((a) => a.riskLevel === "medium").length}
          </p>
          <p className="text-xs text-gray-500">Medium</p>
        </div>
        <div className="text-center">
          <p className="text-2xl font-bold text-emerald-600">
            {visibleAccounts.filter((a) => a.riskLevel === "low").length}
          </p>
          <p className="text-xs text-gray-500">Low</p>
        </div>
      </div>

      {/* At-risk accounts list */}
      <div className="space-y-4 max-h-[500px] overflow-y-auto">
        {visibleAccounts.length === 0 ? (
          <div className="text-center py-8 text-gray-500">
            <AlertTriangle className="h-8 w-8 mx-auto mb-2 text-gray-300" />
            <p>No at-risk accounts to display</p>
            {snoozedCount > 0 && (
              <p className="text-sm mt-1">
                {snoozedCount} accounts are snoozed
              </p>
            )}
          </div>
        ) : (
          visibleAccounts.map((account) => (
            <div
              key={account.tenantId}
              className="p-4 rounded-lg border border-gray-100 hover:border-gray-200 transition-colors"
            >
              {/* Account header */}
              <div className="flex items-start justify-between mb-3">
                <div>
                  <div className="flex items-center gap-2">
                    <h4 className="font-medium text-gray-900">
                      {account.tenantName}
                    </h4>
                    <span
                      className={`px-2 py-0.5 rounded-full text-xs font-medium ${getRiskLevelStyle(account.riskLevel)}`}
                    >
                      {account.riskLevel}
                    </span>
                  </div>
                  <p className="text-xs text-gray-500">{account.tenantEmail}</p>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-lg font-bold tabular-nums text-gray-700">
                    {account.healthScore}
                  </span>
                  <button
                    onClick={() => handleSnooze(account.tenantId)}
                    className="p-1.5 rounded-lg text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
                    title={
                      snoozed.has(account.tenantId)
                        ? "Unsnooze"
                        : "Snooze alert"
                    }
                  >
                    {snoozed.has(account.tenantId) ? (
                      <BellOff className="h-4 w-4" />
                    ) : (
                      <Bell className="h-4 w-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* Risk reasons */}
              <div className="flex flex-wrap gap-2 mb-3">
                {account.riskReasons.map((reason, idx) => (
                  <span
                    key={idx}
                    className={`inline-flex items-center gap-1.5 px-2 py-1 rounded-lg text-xs border ${getReasonBadgeColor(reason.severity)}`}
                  >
                    {getRiskIcon(reason.type)}
                    {reason.detail}
                  </span>
                ))}
              </div>

              {/* Account metadata */}
              <div className="flex items-center gap-4 text-xs text-gray-500 mb-3">
                {account.tier && <span>Tier: {account.tier}</span>}
                <span>MRR: ${account.mrr}</span>
                {account.lastContactedAt && (
                  <span>
                    Last contact:{" "}
                    {new Date(account.lastContactedAt).toLocaleDateString()}
                  </span>
                )}
              </div>

              {/* Playbook actions */}
              <div className="flex flex-wrap gap-2 pt-2 border-t border-gray-100">
                <PlaybookButton
                  type="recovery"
                  tenantId={account.tenantId}
                  onAction={handlePlaybookAction}
                  loading={actionLoading === `recovery-${account.tenantId}`}
                />
                <PlaybookButton
                  type="qbr"
                  tenantId={account.tenantId}
                  onAction={handlePlaybookAction}
                  loading={actionLoading === `qbr-${account.tenantId}`}
                />
                <PlaybookButton
                  type="csm"
                  tenantId={account.tenantId}
                  onAction={handlePlaybookAction}
                  loading={actionLoading === `csm-${account.tenantId}`}
                />
              </div>
            </div>
          ))
        )}
      </div>

      {/* Footer */}
      <div className="mt-4 pt-4 border-t border-gray-100 flex items-center justify-between text-xs text-gray-500">
        <span>
          {data.distribution.atRisk + data.distribution.critical} total at-risk
          accounts
        </span>
        <span>Updated: {new Date(data.calculatedAt).toLocaleTimeString()}</span>
      </div>
    </div>
  );
}
