import React, { useState } from 'react';
import { Head, router, usePage } from '@inertiajs/react';
import AdminLayout from '@/components/layouts/admin-layout';
import { HiSearch, HiFilter, HiRefresh, HiChevronLeft, HiChevronRight, HiClock, HiTerminal } from 'react-icons/hi';
import PopupDetailLog from '@/components/admin/logs/popupDetailLog';

interface User {
  id_user: string;
  username: string;
}

interface LogItem {
  id_log: number;
  id_user: string | null;
  user: User | null;
  action: string;
  description: string;
  ip_address: string | null;
  created_at: string;
}

interface PaginationProps<T> {
  data: T[];
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  from: number;
  to: number;
  links: Array<{
    url: string | null;
    label: string;
    active: boolean;
  }>;
}

interface PageProps {
  logs: PaginationProps<LogItem>;
  filters: {
    search?: string;
    action?: string;
    date_from?: string;
    date_to?: string;
  };
  actionsList: string[];
}

export default function LogsManagement() {
  const { logs, filters = {}, actionsList = [] } = usePage<any>().props as PageProps;

  // Local state untuk filter
  const [search, setSearch] = useState(filters.search || '');
  const [action, setAction] = useState(filters.action || '');
  const [dateFrom, setDateFrom] = useState(filters.date_from || '');
  const [dateTo, setDateTo] = useState(filters.date_to || '');

  // Modal detail payload JSON
  const [selectedPayload, setSelectedPayload] = useState<any>(null);
  const [selectedLog, setSelectedLog] = useState<LogItem | null>(null);

  // Trigger pencarian/filter ke Server
  const handleFilter = (e?: React.FormEvent) => {
    if (e) e.preventDefault();
    router.get(
      '/admin/logs',
      { search, action, date_from: dateFrom, date_to: dateTo },
      { preserveState: true, replace: true }
    );
  };

  // Reset semua filter
  const handleReset = () => {
    setSearch('');
    setAction('');
    setDateFrom('');
    setDateTo('');
    router.get('/admin/logs', {}, { preserveState: true, replace: true });
  };

  // Helper penentu badge warna action
  const getActionBadgeClass = (actionName: string) => {
    if (!actionName) return 'bg-gray-800 text-gray-300 border-gray-700';
    const act = actionName.toUpperCase();
    if (act.includes('LOGIN') || act.includes('CREATE')) return 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20';
    if (act.includes('UPDATE') || act.includes('EDIT')) return 'bg-amber-500/10 text-amber-400 border-amber-500/20';
    if (act.includes('DELETE') || act.includes('LOGOUT')) return 'bg-rose-500/10 text-rose-400 border-rose-500/20';
    return 'bg-blue-500/10 text-blue-400 border-blue-500/20';
  };

  return (
    <div className="space-y-6">

      {/* metadata */}
      <Head>
        <title>Logs Admin</title>
        <meta name="description" content="Seluruh catatan daftar aktivitas sistem yang sedang berjalan." />
        <meta property="og:title" content="Logs Admin" />
      </Head>
      
      {/* FILTER BAR CONTAINER */}
      <div className="p-5 bg-gray-900 border border-gray-800 rounded-xs shadow-xs space-y-4">
        <p className='font-bold'>Filter Log Aktivitis</p>
        <form onSubmit={handleFilter} className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
          
          {/* Search Input */}
          <div className="relative">
            <HiSearch className=" absolute left-3.5 top-2 text-gray-500" />
            <input
              type="text"
              placeholder="Cari deskripsi / user..."
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              className="w-full pl-9 pr-4 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-200 placeholder-gray-500 focus:border-gray-700 focus:outline-none transition"
            />
          </div>

          {/* Action Select */}
          <select
            value={action}
            onChange={(e) => setAction(e.target.value)}
            className="w-full px-3 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-300 focus:border-gray-700 focus:outline-none transition"
          >
            <option value="">Semua Action</option>
            {actionsList.map((act) => (
              <option key={act} value={act}>{act}</option>
            ))}
          </select>

          {/* Date From */}
          <input
            type="date"
            value={dateFrom}
            onChange={(e) => setDateFrom(e.target.value)}
            className="w-full px-3 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-300 focus:border-gray-700 focus:outline-none transition scheme-dark"
          />

          {/* Date To */}
          <input
            type="date"
            value={dateTo}
            onChange={(e) => setDateTo(e.target.value)}
            className="w-full px-3 py-2 bg-gray-950 border border-gray-800 rounded-xl text-xs text-gray-300 focus:border-gray-700 focus:outline-none transition scheme-dark"
          />

        </form>

        {/* Action Buttons */}
        <div className="flex items-center justify-between pt-2 border-t border-gray-800/60">
          <p className="text-xs text-gray-400">
            Menampilkan <span className="font-bold text-gray-200">{logs.from || 0} - {logs.to || 0}</span> dari <span className="font-bold text-gray-200">{logs.total}</span> log
          </p>

          <div className="flex items-center gap-2">
            <button
              type="button"
              onClick={handleReset}
              className="px-3 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 font-semibold text-xs rounded-lg flex items-center gap-1.5 transition cursor-pointer"
            >
              <HiRefresh className="w-3.5 h-3.5" />
              <span>Reset</span>
            </button>

            <button
              type="button"
              onClick={() => handleFilter()}
              className="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold text-xs rounded-lg flex items-center gap-1.5 transition cursor-pointer shadow-xs"
            >
              <HiFilter className="w-3.5 h-3.5" />
              <span>Terapkan Filter</span>
            </button>
          </div>
        </div>
      </div>

      {/* TABLE DATA LOGS */}
      <div className="bg-gray-900 border border-gray-800 rounded-xs overflow-hidden shadow-xs">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="bg-gray-950/80 text-gray-400 uppercase font-semibold border-b border-gray-800">
              <tr>
                <th className="px-4 py-3.5">Waktu</th>
                <th className="px-4 py-3.5">Pengguna</th>
                <th className="px-4 py-3.5">Action</th>
                <th className="px-4 py-3.5">Deskripsi</th>
                <th className="px-4 py-3.5">IP Address</th>
              </tr>
            </thead>

            <tbody className="divide-y divide-gray-800/60 text-gray-300">
              {logs?.data?.length > 0 ? (
                logs.data.map((log) => (
                  <tr key={log.id_log} onClick={() => setSelectedLog(log)} className="hover:bg-gray-800/40 cursor-pointer transition duration-150">
                    
                    {/* Waktu Log */}
                    <td className="px-4 py-3 whitespace-nowrap text-gray-400 font-mono">
                      <div className="flex items-center gap-1.5">
                        <HiClock className="w-3.5 h-3.5 text-gray-500" />
                        <span>
                          {new Date(log.created_at).toLocaleString('id-ID', {
                            day: '2-digit',
                            month: '2-digit',
                            year: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                          })}
                        </span>
                      </div>
                    </td>

                    {/* User */}
                    <td className="px-4 py-3 whitespace-nowrap">
                      {log.user ? (
                        <div>
                          <p className="font-bold text-gray-200">{log.user.username}</p>
                        </div>
                      ) : (
                        <span className="text-gray-500 italic">Sistem / Terhapus</span>
                      )}
                    </td>

                    {/* Action Badge */}
                    <td className="px-4 py-3 whitespace-nowrap">
                      <span className={`px-2.5 py-1 rounded-md text-[10px] font-bold border ${getActionBadgeClass(log.action)}`}>
                        {log.action || '-'}
                      </span>
                    </td>

                    {/* Deskripsi */}
                    <td className="px-4 py-3 max-w-sm truncate" title={log.description}>
                      {log.description}
                    </td>

                    {/* IP Address */}
                    <td className="px-4 py-3 whitespace-nowrap font-mono text-gray-400 text-[11px]">
                      {log.ip_address || '-'}
                    </td>

                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={6} className="px-4 py-8 text-center text-gray-500 italic">
                    Tidak ada data log aktivitas yang ditemukan.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* PAGINATION */}
        {logs?.last_page > 1 && (
          <div className="p-4 border-t border-gray-800 flex items-center justify-between bg-gray-950/60">
            <p className="text-xs text-gray-400">
              Halaman <span className="font-bold text-gray-200">{logs.current_page}</span> dari <span className="font-bold text-gray-200">{logs.last_page}</span>
            </p>

            <div className="flex items-center gap-1">
              {logs.links.map((link, idx) => {
                if (link.label.includes('&laquo;') || link.label.includes('Previous')) {
                  return (
                    <button
                      key={idx}
                      disabled={!link.url}
                      onClick={() => link.url && router.get(link.url, {}, { preserveState: true })}
                      className="p-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-xl disabled:opacity-40 disabled:cursor-not-allowed transition cursor-pointer"
                    >
                      <HiChevronLeft className="w-4 h-4" />
                    </button>
                  );
                }

                if (link.label.includes('&raquo;') || link.label.includes('Next')) {
                  return (
                    <button
                      key={idx}
                      disabled={!link.url}
                      onClick={() => link.url && router.get(link.url, {}, { preserveState: true })}
                      className="p-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-xl disabled:opacity-40 disabled:cursor-not-allowed transition cursor-pointer"
                    >
                      <HiChevronRight className="w-4 h-4" />
                    </button>
                  );
                }

                return (
                  <button
                    key={idx}
                    onClick={() => link.url && router.get(link.url, {}, { preserveState: true })}
                    className={`px-3 py-1.5 text-xs font-semibold rounded-xl transition cursor-pointer ${
                      link.active 
                        ? 'bg-blue-600 text-white' 
                        : 'bg-gray-800/80 text-gray-300 hover:bg-gray-700'
                    }`}
                  >
                    {link.label}
                  </button>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* MODAL VIEW PAYLOAD JSON */}
      {selectedPayload && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/70 backdrop-blur-xs">
          <div className="bg-gray-900 border border-gray-800 w-full max-w-lg rounded-2xl p-5 space-y-4 shadow-2xl">
            <div className="flex items-center justify-between border-b border-gray-800 pb-3">
              <h3 className="text-sm font-bold text-gray-100 flex items-center gap-2">
                <HiTerminal className="w-4 h-4 text-blue-400" />
                Detail Payload Data
              </h3>
              <button
                onClick={() => setSelectedPayload(null)}
                className="text-gray-400 hover:text-white text-xs font-semibold px-2 py-1 bg-gray-800 rounded-lg cursor-pointer"
              >
                Tutup
              </button>
            </div>

            <pre className="p-4 bg-gray-950 border border-gray-800/80 rounded-xl text-[11px] font-mono text-emerald-400 overflow-x-auto max-h-80">
              {JSON.stringify(selectedPayload, null, 2)}
            </pre>
          </div>
        </div>
      )}

      {/* MODAL DETAIL LOG */}
      {selectedLog && (
        <PopupDetailLog
          log={selectedLog}
          onClose={() => setSelectedLog(null)}
        />
      )}

    </div>
  );
}

// Attach Persistent Layout
LogsManagement.layout = (page: React.ReactNode) => (
  <AdminLayout pageName="Log Aktivitas System">
    {page}
  </AdminLayout>
);