"use client";

import { useEffect, useState } from "react";
import {
  Clock,
  RefreshCw,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Activity,
  Calendar,
} from "lucide-react";
import type {
  BackgroundJobsResponse,
  JobQueueStatus,
  CronJobStatus,
} from "@/lib/types/admin-panel";

export function BackgroundJobsClient() {
  const [data, setData] = useState<BackgroundJobsResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [lastRefresh, setLastRefresh] = useState<Date>(new Date());

  const fetchData = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/staff/admin/jobs");
      if (!res.ok) throw new Error("Failed to fetch jobs data");
      const json = await res.json();
      setData(json);
      setLastRefresh(new Date());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Unknown error");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 30000);
    return () => clearInterval(interval);
  }, []);

  const statusColors: Record<string, string> = {
    healthy: "bg-green-100 text-green-800",
    degraded: "bg-yellow-100 text-yellow-800",
    failing: "bg-red-100 text-red-800",
    success: "bg-green-100 text-green-800",
    failed: "bg-red-100 text-red-800",
    running: "bg-blue-100 text-blue-800",
    pending: "bg-gray-100 text-gray-600",
  };

  if (error) {
    return (
      <div className="bg-red-50 border border-red-200 rounded-lg p-6">
        <div className="flex items-center gap-2 text-red-800">
          <XCircle className="w-5 h-5" />
          <span className="font-medium">Error loading jobs data</span>
        </div>
        <p className="text-red-600 mt-2">{error}</p>
        <button
          onClick={fetchData}
          className="mt-4 px-4 py-2 bg-red-100 text-red-800 rounded-lg hover:bg-red-200 transition"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-500">
          Last updated: {lastRefresh.toLocaleTimeString()}
        </p>
        <button
          onClick={fetchData}
          disabled={loading}
          className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-600 hover:text-brand-primary hover:bg-gray-100 rounded-lg transition disabled:opacity-50"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
          Refresh
        </button>
      </div>

      {/* Overall Health */}
      {data && (
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div
            className={`rounded-xl p-6 ${
              data.overall.healthy
                ? "bg-green-50 border border-green-200"
                : "bg-red-50 border border-red-200"
            }`}
          >
            <div className="flex items-center gap-3">
              {data.overall.healthy ? (
                <CheckCircle2 className="w-8 h-8 text-green-600" />
              ) : (
                <XCircle className="w-8 h-8 text-red-600" />
              )}
              <div>
                <p className="text-sm text-gray-600">Overall Status</p>
                <p
                  className={`text-xl font-bold ${
                    data.overall.healthy ? "text-green-700" : "text-red-700"
                  }`}
                >
                  {data.overall.healthy ? "Healthy" : "Issues Detected"}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <div className="flex items-center gap-3">
              <Activity className="w-8 h-8 text-blue-500" />
              <div>
                <p className="text-sm text-gray-600">Active Jobs</p>
                <p className="text-3xl font-bold text-gray-900">
                  {data.overall.totalActive}
                </p>
              </div>
            </div>
          </div>

          <div className="bg-white border border-gray-200 rounded-xl p-6">
            <div className="flex items-center gap-3">
              <AlertTriangle className="w-8 h-8 text-red-500" />
              <div>
                <p className="text-sm text-gray-600">Failed Jobs</p>
                <p className="text-3xl font-bold text-red-600">
                  {data.overall.totalFailed}
                </p>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Queues */}
      <div>
        <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
          <Clock className="w-5 h-5 text-gray-400" />
          Job Queues
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {loading && !data
            ? Array(3)
                .fill(0)
                .map((_, i) => (
                  <div
                    key={i}
                    className="bg-white border border-gray-200 rounded-lg p-4 animate-pulse"
                  >
                    <div className="h-4 bg-gray-200 rounded w-1/2 mb-3" />
                    <div className="h-8 bg-gray-200 rounded w-1/4 mb-2" />
                    <div className="h-3 bg-gray-200 rounded w-3/4" />
                  </div>
                ))
            : data?.queues.map((queue) => (
                <QueueCard
                  key={queue.queueName}
                  queue={queue}
                  statusColors={statusColors}
                />
              ))}
        </div>
      </div>

      {/* Cron Jobs */}
      <div>
        <h3 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
          <Calendar className="w-5 h-5 text-gray-400" />
          Cron Jobs
        </h3>
        <div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
          <table className="w-full">
            <thead className="bg-gray-50 border-b border-gray-200">
              <tr>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">
                  Job Name
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">
                  Schedule
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">
                  Last Run
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">
                  Status
                </th>
                <th className="px-4 py-3 text-left text-xs font-semibold text-gray-600 uppercase">
                  Duration
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100">
              {loading && !data
                ? Array(4)
                    .fill(0)
                    .map((_, i) => (
                      <tr key={i}>
                        <td className="px-4 py-3">
                          <div className="h-4 bg-gray-200 rounded w-24 animate-pulse" />
                        </td>
                        <td className="px-4 py-3">
                          <div className="h-4 bg-gray-200 rounded w-20 animate-pulse" />
                        </td>
                        <td className="px-4 py-3">
                          <div className="h-4 bg-gray-200 rounded w-32 animate-pulse" />
                        </td>
                        <td className="px-4 py-3">
                          <div className="h-4 bg-gray-200 rounded w-16 animate-pulse" />
                        </td>
                        <td className="px-4 py-3">
                          <div className="h-4 bg-gray-200 rounded w-12 animate-pulse" />
                        </td>
                      </tr>
                    ))
                : data?.cronJobs.map((job) => (
                    <CronRow
                      key={job.jobName}
                      job={job}
                      statusColors={statusColors}
                    />
                  ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function QueueCard({
  queue,
  statusColors,
}: {
  queue: JobQueueStatus;
  statusColors: Record<string, string>;
}) {
  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4">
      <div className="flex items-center justify-between mb-3">
        <span className="font-semibold text-gray-900 capitalize">
          {queue.queueName}
        </span>
        <span
          className={`px-2 py-0.5 rounded text-xs font-medium ${statusColors[queue.status]}`}
        >
          {queue.status}
        </span>
      </div>

      <div className="grid grid-cols-2 gap-3 text-sm">
        <div>
          <p className="text-gray-500">Active</p>
          <p className="font-semibold text-gray-900">{queue.activeJobs}</p>
        </div>
        <div>
          <p className="text-gray-500">Waiting</p>
          <p className="font-semibold text-gray-900">{queue.waitingJobs}</p>
        </div>
        <div>
          <p className="text-gray-500">Completed</p>
          <p className="font-semibold text-green-600">{queue.completedJobs}</p>
        </div>
        <div>
          <p className="text-gray-500">Failed</p>
          <p className="font-semibold text-red-600">{queue.failedJobs}</p>
        </div>
      </div>

      {queue.lastFailure && (
        <div className="mt-3 p-2 bg-red-50 rounded text-xs text-red-600">
          Last failure: {queue.lastFailure.error.substring(0, 50)}...
        </div>
      )}
    </div>
  );
}

function CronRow({
  job,
  statusColors,
}: {
  job: CronJobStatus;
  statusColors: Record<string, string>;
}) {
  return (
    <tr className="hover:bg-gray-50">
      <td className="px-4 py-3">
        <span className="font-medium text-gray-900">{job.jobName}</span>
      </td>
      <td className="px-4 py-3">
        <code className="text-xs bg-gray-100 px-2 py-1 rounded">
          {job.schedule}
        </code>
      </td>
      <td className="px-4 py-3 text-sm text-gray-600">
        {job.lastRun ? new Date(job.lastRun).toLocaleString() : "Never"}
      </td>
      <td className="px-4 py-3">
        <span
          className={`px-2 py-0.5 rounded text-xs font-medium ${statusColors[job.lastStatus]}`}
        >
          {job.lastStatus}
        </span>
      </td>
      <td className="px-4 py-3 text-sm text-gray-600">
        {job.lastDuration ? `${job.lastDuration}ms` : "-"}
      </td>
    </tr>
  );
}
