"use client";

import React, { useState, useEffect } from "react";
import {
  ListOrdered,
  Filter,
  Search,
  RotateCw,
  Clock,
  CheckCircle2,
  AlertTriangle,
  XCircle,
  Eye,
  Play,
  RotateCcw,
  ShieldAlert,
} from "lucide-react";

interface JobsQueueViewProps {
  onOpenScreenshot: (job: any) => void;
  onOpenManualModal: (job: any) => void;
  onRunJob: (jobId: number) => void;
}

export const JobsQueueView: React.FC<JobsQueueViewProps> = ({
  onOpenScreenshot,
  onOpenManualModal,
  onRunJob,
}) => {
  const [jobs, setJobs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState("ALL");
  const [search, setSearch] = useState("");
  const [todayDate, setTodayDate] = useState("");

  const fetchJobs = async () => {
    setLoading(true);
    try {
      const url = statusFilter !== "ALL" ? `/api/jobs?status=${statusFilter}` : "/api/jobs";
      const res = await fetch(url);
      const data = await res.json();
      if (data.success) {
        setJobs(data.jobs || []);
        if (data.todayDate) setTodayDate(data.todayDate);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchJobs();
  }, [statusFilter]);

  const handleRetryJob = async (jobId: number) => {
    try {
      await fetch("/api/jobs", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: jobId, action: "retry" }),
      });
      fetchJobs();
    } catch (e) {
      alert("Failed to retry job");
    }
  };

  const handleCancelJob = async (jobId: number) => {
    if (!confirm("Cancel this appointment job?")) return;
    try {
      await fetch("/api/jobs", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ id: jobId, action: "cancel" }),
      });
      fetchJobs();
    } catch (e) {
      alert("Failed to cancel");
    }
  };

  const filtered = jobs.filter((j) => {
    if (!search) return true;
    const q = search.toLowerCase();
    return (
      j.patientName?.toLowerCase().includes(q) ||
      j.mobile?.includes(q) ||
      j.resultSerial?.toLowerCase().includes(q)
    );
  });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h2 className="text-xl font-extrabold text-white flex items-center gap-2">
            <ListOrdered className="w-5 h-5 text-blue-400" />
            Appointment Job Queue &amp; History
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            Full queue audit log with exact target timestamps, captured serials, and retry options.
          </p>
        </div>

        <button
          onClick={fetchJobs}
          className="px-3.5 py-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 text-xs font-semibold flex items-center gap-2 self-start sm:self-auto"
        >
          <RotateCw className="w-3.5 h-3.5" />
          <span>Refresh Queue</span>
        </button>
      </div>

      {/* Filter Bar */}
      <div className="p-4 rounded-2xl bg-slate-900 border border-slate-800 flex flex-col md:flex-row gap-4 justify-between">
        <div className="flex flex-wrap items-center gap-2">
          {["ALL", "Pending", "Running", "Success", "Failed", "Manual Action Required"].map((st) => (
            <button
              key={st}
              onClick={() => setStatusFilter(st)}
              className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition-all ${
                statusFilter === st
                  ? "bg-blue-600 text-white shadow-md shadow-blue-600/20"
                  : "bg-slate-800 text-slate-400 hover:text-white"
              }`}
            >
              {st}
            </button>
          ))}
        </div>

        <div className="relative w-full md:w-64">
          <Search className="w-3.5 h-3.5 text-slate-500 absolute left-3 top-3" />
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search patient, mobile, serial..."
            className="w-full pl-9 pr-3 py-2 bg-slate-950 border border-slate-700 rounded-xl text-xs text-white placeholder-slate-500 focus:outline-none focus:border-blue-500"
          />
        </div>
      </div>

      {/* Jobs Table */}
      <div className="rounded-2xl bg-slate-900 border border-slate-800 overflow-hidden shadow-xl">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead>
              <tr className="border-b border-slate-800 bg-slate-950 text-slate-400 font-semibold uppercase tracking-wider">
                <th className="py-3 px-4">Job ID</th>
                <th className="py-3 px-4">Date</th>
                <th className="py-3 px-4">Slot</th>
                <th className="py-3 px-4">Target Time</th>
                <th className="py-3 px-4">Patient</th>
                <th className="py-3 px-4">Mobile</th>
                <th className="py-3 px-4">Status</th>
                <th className="py-3 px-4">Assigned Serial</th>
                <th className="py-3 px-4 text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-800/60">
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={9} className="py-12 text-center text-slate-500">
                    No jobs found matching criteria.
                  </td>
                </tr>
              ) : (
                filtered.map((job) => (
                  <tr key={job.id} className="hover:bg-slate-800/40 transition-colors">
                    <td className="py-3.5 px-4 font-mono text-slate-400 font-bold">#{job.id}</td>
                    <td className="py-3.5 px-4 font-mono text-slate-300">{job.appointmentDate}</td>
                    <td className="py-3.5 px-4 font-bold text-white">#{job.priorityOrder}</td>
                    <td className="py-3.5 px-4 font-mono text-cyan-400 font-semibold">{job.targetTime}</td>
                    <td className="py-3.5 px-4 font-bold text-white">{job.patientName}</td>
                    <td className="py-3.5 px-4 font-mono text-slate-300">{job.mobile}</td>

                    <td className="py-3.5 px-4">
                      <span
                        className={`inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold ${
                          job.status === "Success"
                            ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20"
                            : job.status === "Manual Action Required"
                            ? "bg-amber-500/10 text-amber-400 border border-amber-500/20"
                            : job.status === "Running"
                            ? "bg-blue-500/10 text-blue-400 animate-pulse border border-blue-500/20"
                            : job.status === "Pending"
                            ? "bg-slate-800 text-slate-300"
                            : "bg-rose-500/10 text-rose-400 border border-rose-500/20"
                        }`}
                      >
                        {job.status}
                      </span>
                    </td>

                    <td className="py-3.5 px-4 font-mono">
                      {job.resultSerial ? (
                        <span className="font-bold text-emerald-400 bg-emerald-950/60 border border-emerald-800/40 px-2 py-0.5 rounded">
                          {job.resultSerial}
                        </span>
                      ) : (
                        <span className="text-slate-600">—</span>
                      )}
                    </td>

                    <td className="py-3.5 px-4 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        {job.screenshotPath && (
                          <button
                            onClick={() => onOpenScreenshot(job)}
                            className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-blue-400 transition-colors"
                            title="View Screenshot"
                          >
                            <Eye className="w-3.5 h-3.5" />
                          </button>
                        )}

                        {job.status === "Manual Action Required" && (
                          <button
                            onClick={() => onOpenManualModal(job)}
                            className="px-2 py-1 rounded-lg bg-amber-500 hover:bg-amber-400 text-slate-950 font-bold text-[11px] transition-colors"
                          >
                            Resolve
                          </button>
                        )}

                        {job.status === "Failed" && (
                          <button
                            onClick={() => handleRetryJob(job.id)}
                            className="p-1.5 rounded-lg bg-slate-800 hover:bg-blue-600 text-slate-200 transition-colors"
                            title="Retry Job"
                          >
                            <RotateCcw className="w-3.5 h-3.5" />
                          </button>
                        )}

                        {job.status === "Pending" && (
                          <button
                            onClick={() => onRunJob(job.id)}
                            className="p-1.5 rounded-lg bg-slate-800 hover:bg-blue-600 text-slate-200 transition-colors"
                            title="Run immediately"
                          >
                            <Play className="w-3.5 h-3.5" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
