"use client";

import { useState, useEffect, useCallback } from "react";
import {
  MessageCircle,
  CreditCard,
  Server,
  AlertCircle,
  CheckCircle,
  AlertTriangle,
  RefreshCw,
  ExternalLink,
  Wifi,
  WifiOff,
} from "lucide-react";

type IntegrationStatus = "healthy" | "degraded" | "down";

interface IntegrationHealth {
  whatsapp: {
    status: IntegrationStatus;
    connected: boolean;
    errorRate: number;
    lastError: string | null;
    lastErrorAt: string | null;
    messagesLast24h: number;
    circuitState: string;
  };
  stripe: {
    status: IntegrationStatus;
    webhookSuccessRate: number;
    lastWebhookAt: string | null;
    lastFailure: string | null;
    paymentsLast24h: number;
  };
  redis: {
    status: IntegrationStatus;
    memoryUsage: number;
    connectionCount: number;
    latency: number;
    configured: boolean;
  };
}

interface IntegrationHealthResponse {
  integrations: IntegrationHealth;
  overall: {
    status: IntegrationStatus;
    healthy: number;
    degraded: number;
    down: number;
  };
  database: {
    status: string;
    latency: number;
  };
  checkedAt: string;
}

// Status badge component
function StatusBadge({ status }: { status: IntegrationStatus }) {
  const config = {
    healthy: {
      bg: "bg-green-100",
      text: "text-green-700",
      icon: CheckCircle,
      label: "Healthy",
    },
    degraded: {
      bg: "bg-yellow-100",
      text: "text-yellow-700",
      icon: AlertTriangle,
      label: "Degraded",
    },
    down: {
      bg: "bg-red-100",
      text: "text-red-700",
      icon: AlertCircle,
      label: "Down",
    },
  };

  const { bg, text, icon: Icon, label } = config[status];

  return (
    <span
      className={`inline-flex items-center gap-1 px-2 py-1 text-xs font-medium rounded-full ${bg} ${text}`}
    >
      <Icon className="h-3 w-3" />
      {label}
    </span>
  );
}

// Individual integration card
function IntegrationItem({
  name,
  icon: Icon,
  status,
  latency,
  metrics,
  error,
  onDrillDown,
}: {
  name: string;
  icon: React.ElementType;
  status: IntegrationStatus;
  latency?: number;
  metrics?: { label: string; value: string | number }[];
  error?: string | null;
  onDrillDown?: () => void;
}) {
  const [expanded, setExpanded] = useState(false);

  return (
    <div
      className={`border rounded-xl p-4 transition-all ${
        status === "down"
          ? "border-red-200 bg-red-50"
          : status === "degraded"
            ? "border-yellow-200 bg-yellow-50"
            : "border-gray-200 bg-white"
      }`}
    >
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div
            className={`p-2 rounded-lg ${
              status === "down"
                ? "bg-red-100"
                : status === "degraded"
                  ? "bg-yellow-100"
                  : "bg-green-100"
            }`}
          >
            <Icon
              className={`h-5 w-5 ${
                status === "down"
                  ? "text-red-600"
                  : status === "degraded"
                    ? "text-yellow-600"
                    : "text-green-600"
              }`}
            />
          </div>
          <div>
            <h4 className="font-medium text-gray-900">{name}</h4>
            {latency !== undefined && (
              <p className="text-xs text-gray-500">{latency}ms latency</p>
            )}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <StatusBadge status={status} />
          <button
            onClick={() => setExpanded(!expanded)}
            className="p-1 text-gray-400 hover:text-gray-600 rounded"
          >
            <svg
              className={`h-4 w-4 transition-transform ${expanded ? "rotate-180" : ""}`}
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M19 9l-7 7-7-7"
              />
            </svg>
          </button>
        </div>
      </div>

      {/* Expanded details */}
      {expanded && (
        <div className="mt-4 pt-4 border-t border-gray-200 space-y-3">
          {/* Metrics */}
          {metrics && metrics.length > 0 && (
            <div className="grid grid-cols-2 gap-2">
              {metrics.map((metric) => (
                <div key={metric.label} className="bg-gray-50 rounded p-2">
                  <div className="text-xs text-gray-500">{metric.label}</div>
                  <div className="text-sm font-medium text-gray-900">
                    {metric.value}
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Last error */}
          {error && (
            <div className="p-2 bg-red-50 border border-red-200 rounded text-sm">
              <div className="text-xs text-red-600 font-medium mb-1">
                Last Error
              </div>
              <div className="text-red-800">{error}</div>
            </div>
          )}

          {/* Actions */}
          {onDrillDown && (
            <button
              onClick={onDrillDown}
              className="inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800"
            >
              View logs <ExternalLink className="h-3 w-3" />
            </button>
          )}
        </div>
      )}
    </div>
  );
}

// Loading skeleton
function LoadingSkeleton() {
  return (
    <div className="animate-pulse space-y-4">
      <div className="h-6 w-48 bg-gray-200 rounded" />
      <div className="space-y-3">
        {[1, 2, 3, 4].map((i) => (
          <div key={i} className="h-20 bg-gray-200 rounded-xl" />
        ))}
      </div>
    </div>
  );
}

export function IntegrationHealthCard() {
  const [data, setData] = useState<IntegrationHealthResponse | 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/integrations", {
        credentials: "include",
      });

      if (!response.ok) {
        throw new Error("Failed to fetch integration health");
      }

      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 minute
    const interval = setInterval(fetchData, 60000);
    return () => clearInterval(interval);
  }, [fetchData]);

  if (loading) {
    return (
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <LoadingSkeleton />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
        <div className="text-center py-8">
          <AlertCircle className="h-8 w-8 mx-auto mb-2 text-red-500" />
          <p className="text-gray-600">{error}</p>
          <button
            onClick={fetchData}
            className="mt-4 inline-flex items-center gap-2 px-4 py-2 text-sm font-medium text-white bg-brand-green rounded-lg hover:bg-green-700"
          >
            <RefreshCw className="h-4 w-4" />
            Retry
          </button>
        </div>
      </div>
    );
  }

  if (!data) return null;

  const { integrations, overall } = data;

  return (
    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
      {/* Header */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <div
            className={`p-2 rounded-lg ${
              overall.down > 0
                ? "bg-red-100"
                : overall.degraded > 0
                  ? "bg-yellow-100"
                  : "bg-green-100"
            }`}
          >
            {overall.down > 0 ? (
              <WifiOff className="h-5 w-5 text-red-600" />
            ) : (
              <Wifi className="h-5 w-5 text-green-600" />
            )}
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Integration Health
            </h3>
            <p className="text-sm text-gray-500">
              {overall.healthy}/
              {overall.healthy + overall.degraded + overall.down} services
              healthy
            </p>
          </div>
        </div>

        <button
          onClick={fetchData}
          className="p-1.5 text-gray-500 hover:text-gray-700 rounded-lg hover:bg-gray-100"
          title="Refresh"
        >
          <RefreshCw className="h-4 w-4" />
        </button>
      </div>

      {/* Integration list */}
      <div className="space-y-3">
        {/* WhatsApp */}
        <IntegrationItem
          name="WhatsApp Business API"
          icon={MessageCircle}
          status={integrations.whatsapp.status}
          metrics={[
            {
              label: "Messages (24h)",
              value: integrations.whatsapp.messagesLast24h.toLocaleString(),
            },
            {
              label: "Error Rate",
              value: `${integrations.whatsapp.errorRate.toFixed(1)}%`,
            },
            {
              label: "Connected",
              value: integrations.whatsapp.connected ? "Yes" : "No",
            },
            {
              label: "Circuit",
              value: integrations.whatsapp.circuitState,
            },
          ]}
          error={integrations.whatsapp.lastError}
        />

        {/* Stripe */}
        <IntegrationItem
          name="Stripe"
          icon={CreditCard}
          status={integrations.stripe.status}
          metrics={[
            {
              label: "Webhook Success",
              value: `${integrations.stripe.webhookSuccessRate.toFixed(1)}%`,
            },
            {
              label: "Payments (24h)",
              value: integrations.stripe.paymentsLast24h.toLocaleString(),
            },
            {
              label: "Last Webhook",
              value: integrations.stripe.lastWebhookAt
                ? new Date(
                    integrations.stripe.lastWebhookAt,
                  ).toLocaleTimeString()
                : "Never",
            },
          ]}
          error={integrations.stripe.lastFailure}
        />

        {/* Redis */}
        <IntegrationItem
          name="Redis"
          icon={Server}
          status={integrations.redis.status}
          latency={integrations.redis.latency}
          metrics={[
            {
              label: "Configured",
              value: integrations.redis.configured ? "Yes" : "No",
            },
            {
              label: "Connections",
              value: integrations.redis.connectionCount,
            },
          ]}
        />
      </div>

      {/* Footer - last checked */}
      <div className="mt-4 pt-4 border-t border-gray-100 text-xs text-gray-500 text-center">
        Last checked: {new Date(data.checkedAt).toLocaleString()}
      </div>
    </div>
  );
}

export default IntegrationHealthCard;
