"use client";

import React, { useState, useEffect } from "react";
import {
  ScrollText,
  Search,
  RotateCw,
  Trash2,
  CheckCircle2,
  AlertTriangle,
  XCircle,
  Info,
  ShieldAlert,
  Download,
} from "lucide-react";

export const LogsView: React.FC = () => {
  const [logs, setLogs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState("ALL");
  const [autoRefresh, setAutoRefresh] = useState(true);

  const fetchLogs = async () => {
    try {
      let url = "/api/logs?limit=150";
      if (statusFilter !== "ALL") url += `&status=${statusFilter}`;
      if (search) url += `&search=${encodeURIComponent(search)}`;

      const res = await fetch(url);
      const data = await res.json();
      if (data.success) {
        setLogs(data.logs || []);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    if (!autoRefresh) return;
    const interval = setInterval(fetchLogs, 5000);
    return () => clearInterval(interval);
  }, [autoRefresh, statusFilter, search]);

  const handleClearLogs = async () => {
    if (!confirm("Are you sure you want to clear all automation logs?")) return;
    try {
      await fetch("/api/logs", { method: "DELETE" });
      fetchLogs();
    } catch (e) {
      alert("Failed to clear logs");
    }
  };

  const handleExportLogs = () => {
    const text = logs
      .map(
        (l) =>
          `[${new Date(l.createdAt).toLocaleString("en-US", { timeZone: "Asia/Dhaka" })}] [${l.status}] [${l.action}] [Job #${l.jobId || "N/A"}] (${l.patientName || "System"}): ${l.message}`
      )
      .join("\n");

    const blob = new Blob([text], { type: "text/plain" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `automation-logs-${new Date().toISOString().slice(0, 10)}.txt`;
    a.click();
    window.URL.revokeObjectURL(url);
  };

  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">
            <ScrollText className="w-5 h-5 text-blue-400" />
            Automation Activity &amp; Audit Logs
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            Real-time execution telemetry from the Playwright browser worker and daily cron dispatcher.
          </p>
        </div>

        <div className="flex items-center gap-2">
          <button
            onClick={() => setAutoRefresh(!autoRefresh)}
            className={`px-3 py-1.5 rounded-xl border text-xs font-semibold flex items-center gap-1.5 transition-all ${
              autoRefresh
                ? "bg-emerald-500/15 text-emerald-400 border-emerald-500/30"
                : "bg-slate-800 text-slate-400 border-slate-700"
            }`}
          >
            <span className={`w-2 h-2 rounded-full ${autoRefresh ? "bg-emerald-400 animate-pulse" : "bg-slate-500"}`} />
            <span>Auto Refresh (5s)</span>
          </button>

          <button
            onClick={handleExportLogs}
            className="p-2 rounded-xl bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 transition-colors"
            title="Export Logs TXT"
          >
            <Download className="w-4 h-4" />
          </button>

          <button
            onClick={handleClearLogs}
            className="p-2 rounded-xl bg-slate-800 hover:bg-rose-950/60 text-rose-400 border border-slate-700 transition-colors"
            title="Clear Logs"
          >
            <Trash2 className="w-4 h-4" />
          </button>
        </div>
      </div>

      {/* Filter & Search */}
      <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", "INFO", "SUCCESS", "WARNING", "ERROR", "MANUAL_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 logs..."
            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>

      {/* Logs 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 w-28">Time (Dhaka)</th>
                <th className="py-3 px-4 w-20">Job ID</th>
                <th className="py-3 px-4 w-32">Patient</th>
                <th className="py-3 px-4 w-28">Action</th>
                <th className="py-3 px-4 w-24">Status</th>
                <th className="py-3 px-4">Message / Diagnostic</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-800/60 font-mono text-[11px]">
              {logs.length === 0 ? (
                <tr>
                  <td colSpan={6} className="py-12 text-center text-slate-500 font-sans">
                    No logs available.
                  </td>
                </tr>
              ) : (
                logs.map((log) => {
                  const timeStr = new Date(log.createdAt).toLocaleTimeString("en-US", {
                    timeZone: "Asia/Dhaka",
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit",
                  });
                  return (
                    <tr key={log.id} className="hover:bg-slate-800/30 transition-colors">
                      <td className="py-2.5 px-4 text-cyan-400 font-semibold whitespace-nowrap">
                        {timeStr}
                      </td>
                      <td className="py-2.5 px-4 text-slate-400">
                        {log.jobId ? `#${log.jobId}` : "—"}
                      </td>
                      <td className="py-2.5 px-4 text-slate-200 truncate max-w-[150px]">
                        {log.patientName || "Worker Daemon"}
                      </td>
                      <td className="py-2.5 px-4 font-bold text-slate-300">
                        {log.action}
                      </td>
                      <td className="py-2.5 px-4">
                        <span
                          className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold ${
                            log.status === "SUCCESS"
                              ? "bg-emerald-500/15 text-emerald-400"
                              : log.status === "ERROR"
                              ? "bg-rose-500/15 text-rose-400"
                              : log.status === "WARNING"
                              ? "bg-amber-500/15 text-amber-400"
                              : log.status === "MANUAL_REQUIRED"
                              ? "bg-purple-500/15 text-purple-400"
                              : "bg-slate-800 text-slate-400"
                          }`}
                        >
                          {log.status}
                        </span>
                      </td>
                      <td className="py-2.5 px-4 text-slate-300 font-sans text-xs">
                        {log.message}
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};
