"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Users,
  AlertTriangle,
  RefreshCw,
  UserMinus,
  Activity,
  Mail,
} from "lucide-react";
import { Skeleton } from "@/components/ui/skeleton";

interface SeatUtilizationMetrics {
  total: {
    purchased: number;
    active: number;
    utilizationRate: number;
  };
  byTenant: Array<{
    tenantId: string;
    tenantName: string;
    purchased: number;
    active: number;
    utilizationRate: number;
    lastActiveAt: string | null;
  }>;
  underutilized: Array<{
    tenantId: string;
    tenantName: string;
    utilizationRate: number;
    daysSinceLastActive: number;
  }>;
  meta: {
    totalTenants: number;
    underutilizedCount: number;
    activityWindow: string;
    calculatedAt: string;
  };
}

// Gauge component for utilization
function UtilizationGauge({ value }: { value: number }) {
  const color =
    value >= 70
      ? "text-emerald-500"
      : value >= 50
        ? "text-amber-500"
        : "text-red-500";
  const bgColor =
    value >= 70
      ? "stroke-emerald-500"
      : value >= 50
        ? "stroke-amber-500"
        : "stroke-red-500";

  return (
    <div className="relative w-24 h-12 mx-auto">
      <svg viewBox="0 0 100 50" className="w-full h-full">
        {/* Background arc */}
        <path
          d="M 10 50 A 40 40 0 0 1 90 50"
          fill="none"
          stroke="#e5e7eb"
          strokeWidth="8"
          strokeLinecap="round"
        />
        {/* Value arc */}
        <path
          d="M 10 50 A 40 40 0 0 1 90 50"
          fill="none"
          className={bgColor}
          strokeWidth="8"
          strokeLinecap="round"
          strokeDasharray={`${value * 1.26} 126`}
        />
      </svg>
      <div className="absolute inset-x-0 bottom-0 text-center">
        <span className={`text-lg font-bold tabular-nums ${color}`}>
          {value.toFixed(0)}%
        </span>
      </div>
    </div>
  );
}

// Loading skeleton
function SeatUtilizationSkeleton() {
  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-6 mb-4">
        <Skeleton className="h-20" />
        <Skeleton className="h-20" />
      </div>
      <Skeleton className="h-32" />
    </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 seat 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 SeatUtilizationCard() {
  const [data, setData] = useState<SeatUtilizationMetrics | 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/seat-utilization");
      if (!response.ok) {
        throw new Error("Failed to fetch seat utilization data");
      }
      const result = await response.json();
      setData(result);
    } 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 <SeatUtilizationSkeleton />;
  if (error) return <ErrorState message={error} onRetry={fetchData} />;
  if (!data) return null;

  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-blue-100 p-3">
            <Users className="h-6 w-6 text-blue-600" />
          </div>
          <div>
            <h3 className="text-lg font-semibold text-gray-900">
              Seat Utilization
            </h3>
            <p className="text-xs text-gray-500">7-day activity window</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>

      {/* Overall utilization gauge */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex-1">
          <UtilizationGauge value={data.total.utilizationRate} />
          <p className="text-xs text-center text-gray-500 mt-2">
            Overall Utilization
          </p>
        </div>
        <div className="flex-1 grid grid-cols-2 gap-4 text-center">
          <div>
            <div className="flex items-center justify-center gap-1">
              <Activity className="h-4 w-4 text-emerald-500" />
              <span className="text-2xl font-bold text-gray-900 tabular-nums">
                {data.total.active}
              </span>
            </div>
            <p className="text-xs text-gray-500">Active</p>
          </div>
          <div>
            <div className="flex items-center justify-center gap-1">
              <Users className="h-4 w-4 text-gray-400" />
              <span className="text-2xl font-bold text-gray-900 tabular-nums">
                {data.total.purchased}
              </span>
            </div>
            <p className="text-xs text-gray-500">Total Seats</p>
          </div>
        </div>
      </div>

      {/* Underutilized accounts */}
      {data.underutilized.length > 0 && (
        <div className="border-t border-gray-100 pt-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <UserMinus className="h-4 w-4 text-amber-500" />
              <span className="text-sm font-medium text-gray-700">
                Underutilized Accounts
              </span>
            </div>
            <span className="text-xs text-amber-600 font-medium">
              {data.meta.underutilizedCount} total
            </span>
          </div>

          <div className="space-y-2 max-h-32 overflow-y-auto">
            {data.underutilized.slice(0, 5).map((tenant) => (
              <div
                key={tenant.tenantId}
                className="flex items-center justify-between p-2 rounded-lg bg-amber-50 hover:bg-amber-100 transition-colors"
              >
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-gray-900 truncate">
                    {tenant.tenantName}
                  </p>
                  <p className="text-xs text-gray-500">
                    {tenant.daysSinceLastActive === 999
                      ? "Never active"
                      : `${tenant.daysSinceLastActive}d since last login`}
                  </p>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-sm font-semibold text-amber-600 tabular-nums">
                    {tenant.utilizationRate.toFixed(0)}%
                  </span>
                  <button
                    className="rounded-lg p-1.5 text-amber-600 hover:bg-amber-200 transition-colors"
                    title="Send activation reminder"
                  >
                    <Mail className="h-4 w-4" />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Empty state */}
      {data.underutilized.length === 0 && (
        <div className="border-t border-gray-100 pt-4">
          <div className="flex items-center justify-center gap-2 py-4 text-emerald-600">
            <Activity className="h-5 w-5" />
            <span className="text-sm font-medium">
              All accounts actively using seats
            </span>
          </div>
        </div>
      )}

      {/* Footer */}
      <div className="mt-4 flex items-center justify-between text-xs text-gray-500">
        <span>{data.meta.totalTenants} organizations</span>
        <span>
          Updated: {new Date(data.meta.calculatedAt).toLocaleTimeString()}
        </span>
      </div>
    </div>
  );
}
