"use client";

import { useEffect, useState } from "react";
import {
  Activity,
  AlertTriangle,
  CheckCircle2,
  Clock,
  Database,
  Search,
  Server,
  XCircle,
  Loader2,
} from "lucide-react";
import type {
  SystemOverview,
  UserLookupResult,
  ErrorEntry,
  BackgroundJobsResponse,
} from "@/lib/types/admin-panel";

export function AdminPanelClient() {
  const [systemData, setSystemData] = useState<SystemOverview | null>(null);
  const [jobsData, setJobsData] = useState<BackgroundJobsResponse | null>(null);
  const [errors, setErrors] = useState<ErrorEntry[]>([]);
  const [loading, setLoading] = useState(true);
  const [userQuery, setUserQuery] = useState("");
  const [userResult, setUserResult] = useState<UserLookupResult | null>(null);
  const [userSearchLoading, setUserSearchLoading] = useState(false);

  // Fetch system overview and jobs data on mount
  useEffect(() => {
    async function fetchData() {
      try {
        const [systemRes, jobsRes, errorsRes] = await Promise.all([
          fetch("/api/staff/admin/system-overview"),
          fetch("/api/staff/admin/jobs"),
          fetch("/api/staff/admin/errors?limit=5"),
        ]);

        if (systemRes.ok) {
          const data = await systemRes.json();
          setSystemData(data);
        }

        if (jobsRes.ok) {
          const data = await jobsRes.json();
          setJobsData(data);
        }

        if (errorsRes.ok) {
          const data = await errorsRes.json();
          setErrors(data.errors || []);
        }
      } catch (error) {
        console.error("Failed to fetch admin data:", error);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  // Handle user lookup
  const handleUserLookup = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!userQuery.trim()) return;

    setUserSearchLoading(true);
    setUserResult(null);

    try {
      const res = await fetch(
        `/api/staff/admin/user-lookup?query=${encodeURIComponent(userQuery)}`,
      );

      if (res.ok) {
        const data = await res.json();
        setUserResult(data);
      } else {
        const error = await res.json();
        alert(error.error || "User not found");
      }
    } catch (error) {
      console.error("User lookup failed:", error);
      alert("Failed to search for user");
    } finally {
      setUserSearchLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-8 h-8 animate-spin text-brand-primary" />
      </div>
    );
  }

  return (
    <div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
      {/* System Overview Widget */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center gap-2 mb-4">
          <Server className="w-5 h-5 text-brand-primary" />
          <h2 className="text-lg font-semibold text-gray-900">
            System Overview
          </h2>
        </div>

        {systemData ? (
          <div className="space-y-4">
            <div className="flex items-center justify-between text-sm">
              <span className="text-gray-600">Version</span>
              <span className="font-mono text-gray-900">
                {systemData.version}
              </span>
            </div>

            {systemData.commit && (
              <div className="flex items-center justify-between text-sm">
                <span className="text-gray-600">Commit</span>
                <span className="font-mono text-gray-900">
                  {systemData.commit.substring(0, 8)}
                </span>
              </div>
            )}

            <div className="flex items-center justify-between text-sm">
              <span className="text-gray-600">Uptime</span>
              <span className="font-mono text-gray-900">
                {Math.floor(systemData.uptime / 60)}m
              </span>
            </div>

            <div className="border-t pt-4 space-y-3">
              <ServiceStatus
                name="Database"
                status={systemData.database}
                icon={Database}
              />
              <ServiceStatus
                name="Redis"
                status={systemData.redis}
                icon={Activity}
              />
            </div>

            <div className="flex items-center justify-between text-sm pt-2 border-t">
              <span className="text-gray-600">Rate Limiter</span>
              <span
                className={`text-xs px-2 py-1 rounded ${
                  systemData.rateLimiter.healthy
                    ? "bg-green-100 text-green-800"
                    : "bg-yellow-100 text-yellow-800"
                }`}
              >
                {systemData.rateLimiter.mode}
              </span>
            </div>
          </div>
        ) : (
          <p className="text-gray-500 text-sm">Failed to load system data</p>
        )}
      </div>

      {/* User Lookup Widget */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center gap-2 mb-4">
          <Search className="w-5 h-5 text-brand-primary" />
          <h2 className="text-lg font-semibold text-gray-900">User Lookup</h2>
        </div>

        <form onSubmit={handleUserLookup} className="space-y-4">
          <div className="flex gap-2">
            <input
              type="text"
              aria-label="Search by email, phone, or user ID"
              value={userQuery}
              onChange={(e) => setUserQuery(e.target.value)}
              placeholder="Email, phone, or user ID..."
              className="flex-1 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-brand-primary focus:border-transparent"
            />
            <button
              type="submit"
              disabled={userSearchLoading || !userQuery.trim()}
              className="px-4 py-2 bg-brand-primary text-white rounded-md hover:bg-brand-primary/90 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {userSearchLoading ? (
                <Loader2 className="w-5 h-5 animate-spin" />
              ) : (
                "Search"
              )}
            </button>
          </div>

          {userResult && (
            <div className="border border-gray-200 rounded-lg p-4 space-y-2">
              <div className="flex items-center justify-between">
                <span className="font-semibold text-gray-900">
                  {userResult.name}
                </span>
                <span
                  className={`text-xs px-2 py-1 rounded ${
                    userResult.isActive
                      ? "bg-green-100 text-green-800"
                      : "bg-red-100 text-red-800"
                  }`}
                >
                  {userResult.isActive ? "Active" : "Inactive"}
                </span>
              </div>
              <div className="text-sm text-gray-600">{userResult.email}</div>
              {userResult.phone && (
                <div className="text-sm text-gray-600">{userResult.phone}</div>
              )}
              {userResult.subscriptionTier && (
                <div className="flex items-center gap-2 text-sm">
                  <span className="text-gray-600">Tier:</span>
                  <span className="font-medium text-brand-primary">
                    {userResult.subscriptionTier}
                  </span>
                </div>
              )}
            </div>
          )}
        </form>
      </div>

      {/* Recent Errors Widget */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center gap-2 mb-4">
          <AlertTriangle className="w-5 h-5 text-red-500" />
          <h2 className="text-lg font-semibold text-gray-900">Recent Errors</h2>
        </div>

        {errors.length > 0 ? (
          <div className="space-y-3">
            {errors.map((error) => (
              <div
                key={error.id}
                className="border-l-4 border-red-400 pl-3 py-2"
              >
                <div className="flex items-start justify-between gap-2">
                  <div className="flex-1">
                    <p className="text-sm font-medium text-gray-900 line-clamp-1">
                      {error.errorMessage}
                    </p>
                    <p className="text-xs text-gray-500 mt-1">
                      {error.route} •{" "}
                      {new Date(error.timestamp).toLocaleString()}
                    </p>
                  </div>
                  <span
                    className={`text-xs px-2 py-1 rounded flex-shrink-0 ${
                      error.severity === "critical"
                        ? "bg-red-100 text-red-800"
                        : error.severity === "high"
                          ? "bg-orange-100 text-orange-800"
                          : "bg-yellow-100 text-yellow-800"
                    }`}
                  >
                    {error.severity}
                  </span>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-gray-500 text-sm flex items-center gap-2">
            <CheckCircle2 className="w-4 h-4 text-green-500" />
            No recent errors
          </p>
        )}
      </div>

      {/* Background Jobs Widget */}
      <div className="bg-white border border-gray-200 rounded-lg p-6">
        <div className="flex items-center gap-2 mb-4">
          <Clock className="w-5 h-5 text-brand-primary" />
          <h2 className="text-lg font-semibold text-gray-900">
            Background Jobs
          </h2>
        </div>

        {jobsData ? (
          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <span className="text-sm text-gray-600">Overall Health</span>
              <span
                className={`flex items-center gap-1 text-sm font-medium ${
                  jobsData.overall.healthy ? "text-green-600" : "text-red-600"
                }`}
              >
                {jobsData.overall.healthy ? (
                  <CheckCircle2 className="w-4 h-4" />
                ) : (
                  <XCircle className="w-4 h-4" />
                )}
                {jobsData.overall.healthy ? "Healthy" : "Issues Detected"}
              </span>
            </div>

            <div className="grid grid-cols-2 gap-4 pt-2 border-t">
              <div>
                <p className="text-xs text-gray-500">Active Jobs</p>
                <p className="text-2xl font-bold text-gray-900">
                  {jobsData.overall.totalActive}
                </p>
              </div>
              <div>
                <p className="text-xs text-gray-500">Failed Jobs</p>
                <p className="text-2xl font-bold text-red-600">
                  {jobsData.overall.totalFailed}
                </p>
              </div>
            </div>

            {jobsData.queues.length > 0 && (
              <div className="border-t pt-3 space-y-2">
                <p className="text-xs font-semibold text-gray-700 uppercase">
                  Queues
                </p>
                {jobsData.queues.slice(0, 3).map((queue) => (
                  <div
                    key={queue.queueName}
                    className="flex items-center justify-between text-sm"
                  >
                    <span className="text-gray-600 capitalize">
                      {queue.queueName}
                    </span>
                    <span
                      className={`text-xs px-2 py-1 rounded ${
                        queue.status === "healthy"
                          ? "bg-green-100 text-green-800"
                          : queue.status === "degraded"
                            ? "bg-yellow-100 text-yellow-800"
                            : "bg-red-100 text-red-800"
                      }`}
                    >
                      {queue.status}
                    </span>
                  </div>
                ))}
              </div>
            )}
          </div>
        ) : (
          <p className="text-gray-500 text-sm">Failed to load jobs data</p>
        )}
      </div>
    </div>
  );
}

// Helper component for service status
function ServiceStatus({
  name,
  status,
  icon: Icon,
}: {
  name: string;
  status: { healthy: boolean; latency?: number; error?: string };
  icon: React.ComponentType<{ className?: string }>;
}) {
  return (
    <div className="flex items-center justify-between">
      <div className="flex items-center gap-2">
        <Icon className="w-4 h-4 text-gray-400" />
        <span className="text-sm text-gray-600">{name}</span>
      </div>
      <div className="flex items-center gap-2">
        {status.latency !== undefined && (
          <span className="text-xs text-gray-500">{status.latency}ms</span>
        )}
        <span
          className={`w-2 h-2 rounded-full ${
            status.healthy ? "bg-green-500" : "bg-red-500"
          }`}
        />
      </div>
    </div>
  );
}
