/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import React from "react";
import { User, Permit } from "../types";
import { formatIndonesianDate, getApiUrl } from "../utils";
import { Check, X, Loader2, Award, ClipboardList, AlertCircle, FileCheck, CheckSquare, ShieldClose } from "lucide-react";

interface DashboardGuruMapelProps {
  currentUser: User;
  refreshPermitsTrigger: () => void;
  allPermits: Permit[];
}

export default function DashboardGuruMapel({ currentUser, refreshPermitsTrigger, allPermits }: DashboardGuruMapelProps) {
  const [loadingActionId, setLoadingActionId] = React.useState<string | null>(null);
  const [rejectingPermitId, setRejectingPermitId] = React.useState<string | null>(null);
  const [rejectReason, setRejectReason] = React.useState("");

  // Filters
  const pendingRequests = allPermits.filter(
    p => p.mapelTeacherId === currentUser.id && p.statusMapel === "pending"
  );

  const historyRequests = allPermits.filter(
    p => p.mapelTeacherId === currentUser.id && p.statusMapel !== "pending"
  );

  const handleApprove = async (id: string) => {
    setLoadingActionId(id);
    try {
      const res = await fetch(getApiUrl(`permits/${id}/approve-mapel`), {
        method: "POST"
      });
      if (!res.ok) throw new Error("Gagal menyetujui izin");
      refreshPermitsTrigger();
    } catch (err) {
      alert("Error: " + err);
    } finally {
      setLoadingActionId(null);
    }
  };

  const handleRejectSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!rejectingPermitId || !rejectReason.trim()) return;

    setLoadingActionId(rejectingPermitId);
    try {
      const res = await fetch(getApiUrl(`permits/${rejectingPermitId}/reject`), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ rejectReason, rejectedBy: "mapel" })
      });
      if (!res.ok) throw new Error("Gagal menolak izin");
      setRejectingPermitId(null);
      setRejectReason("");
      refreshPermitsTrigger();
    } catch (err) {
      alert("Error: " + err);
    } finally {
      setLoadingActionId(null);
    }
  };

  const getStatusStyle = (status: string) => {
    if (status === "approved") return "bg-emerald-50 text-emerald-800 border-emerald-200";
    if (status === "rejected") return "bg-red-50 text-red-800 border-red-200";
    return "bg-slate-50 text-slate-600";
  };

  return (
    <div className="space-y-8 animate-fade-in text-slate-800">
      {/* Pending Banner List */}
      <section className="space-y-4">
        <div>
          <h2 className="text-base font-bold text-slate-900 flex items-center gap-2">
            <ClipboardList className="h-5 w-5 text-indigo-600" />
            Pengajuan Izin Siswa Baru (Menunggu Verifikasi Anda)
          </h2>
          <p className="text-[11px] text-slate-500 mt-0.5">Sebagai Guru Mata Pelajaran, Anda memverifikasi alur awal apakah murid bebas akademik di jam mengajar Anda.</p>
        </div>

        {pendingRequests.length === 0 ? (
          <div className="bg-white border border-slate-200 rounded-2xl p-10 flex flex-col items-center justify-center text-center shadow-sm">
            <FileCheck className="h-10 w-10 text-emerald-500 mb-3" />
            <p className="text-sm font-semibold text-slate-700">Tugas Verifikasi Bersih!</p>
            <p className="text-xs text-slate-500 max-w-sm font-sans mt-0.5">Semua permohonan siswa yang mengarah ke mata pelajaran Anda telah selesai diproses.</p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {pendingRequests.map(p => (
              <div key={p.id} className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm hover:shadow-md transition-all flex flex-col relative overflow-hidden">
                {/* Accent Tag */}
                <div className="absolute top-0 left-0 right-0 h-1 bg-indigo-600"></div>

                <div className="flex justify-between items-start mb-3 border-b border-slate-100 pb-2.5">
                  <div>
                    <h3 className="text-xs font-bold text-indigo-600 tracking-wide">{p.siswaClass}</h3>
                    <p className="text-sm font-bold text-slate-900 mt-0.5">{p.siswaName}</p>
                    <p className="text-[9px] text-slate-400 font-mono">NISN: {p.siswaInduk}</p>
                  </div>
                  <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase ${
                    p.permitType === "keluar_masuk" ? "bg-indigo-50 text-indigo-700 pr-2 border-indigo-100 border" : "bg-amber-50 text-amber-800 border border-amber-100"
                  }`}>
                    {p.permitType === "keluar_masuk" ? "Izin Keluar-Masuk" : "Pulang Cepat"}
                  </span>
                </div>

                <div className="space-y-2 text-xs text-slate-600 flex-1">
                  <div>
                    <span className="text-[10px] uppercase font-bold text-slate-400 block tracking-widest">Rencana Waktu:</span>
                    <p className="font-semibold text-slate-850">
                      {p.day}, {formatIndonesianDate(p.date)} @ <span className="font-mono text-indigo-600 font-bold">{p.timeExitProposed} s/d {p.timeReturnProposed || "Selesai"}</span>
                    </p>
                  </div>

                  <div>
                    <span className="text-[10px] uppercase font-bold text-slate-400 block tracking-widest">Keterangan / Alasan:</span>
                    <p className="font-sans italic text-slate-800 mt-0.5 font-medium">"{p.reason}"</p>
                  </div>

                  <div className="bg-slate-50 p-2 rounded-lg border border-slate-100 text-[11px]">
                    <span className="font-semibold text-slate-700">Verifikator 2 (Guru Piket):</span>
                    <span className="text-slate-500 block">{p.piketTeacherName}</span>
                  </div>
                </div>

                {/* Approve/Reject triggers */}
                {rejectingPermitId === p.id ? (
                  <form onSubmit={handleRejectSubmit} className="mt-4 pt-3 border-t border-slate-100 space-y-2">
                    <label className="block text-[10px] font-bold text-rose-700 uppercase">Sebutkan Alasan Penolakan:</label>
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={rejectReason}
                        onChange={(e) => setRejectReason(e.target.value)}
                        placeholder="Contoh: Ada kuis atau ulangan mapel bersangkutan..."
                        className="flex-1 bg-slate-50 border border-rose-200 rounded px-2.5 py-1.5 text-xs focus:ring-1 focus:outline-hidden focus:ring-rose-500 text-slate-800"
                        required
                      />
                      <button
                        type="submit"
                        className="px-3 py-1.5 bg-rose-600 hover:bg-rose-700 text-white text-xs font-semibold rounded cursor-pointer shrink-0"
                      >
                        Kirim
                      </button>
                      <button
                        type="button"
                        onClick={() => setRejectingPermitId(null)}
                        className="px-2 py-1.5 bg-slate-200 hover:bg-slate-300 text-slate-700 text-xs font-semibold rounded cursor-pointer shrink-0"
                      >
                        Batal
                      </button>
                    </div>
                  </form>
                ) : (
                  <div className="mt-5 pt-3 border-t border-slate-100 flex gap-2">
                    <button
                      id={`mapel-btn-approve-${p.id}`}
                      disabled={loadingActionId !== null}
                      onClick={() => handleApprove(p.id)}
                      className="flex-1 bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2 rounded-lg text-xs transition-colors flex items-center justify-center gap-1 cursor-pointer shadow-xs"
                    >
                      {loadingActionId === p.id ? (
                        <Loader2 className="h-4 w-4 animate-spin text-white" />
                      ) : (
                        <Check className="h-4 w-4" />
                      )}
                      Setujui
                    </button>
                    
                    <button
                      id={`mapel-btn-reject-${p.id}`}
                      disabled={loadingActionId !== null}
                      onClick={() => setRejectingPermitId(p.id)}
                      className="px-3 bg-rose-50 hover:bg-rose-100 border border-rose-200 text-rose-600 font-semibold py-2 rounded-lg text-xs transition-colors flex items-center justify-center gap-1 cursor-pointer"
                    >
                      <X className="h-4 w-4" />
                      Tolak
                    </button>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </section>

      {/* History */}
      <section className="space-y-4">
        <div>
          <h2 className="text-sm font-bold text-slate-900">Riwayat Verifikasi Anda</h2>
          <p className="text-[11px] text-slate-500 mt-0.5 font-sans">Daftar murid yang telah Anda konfirmasi izinnya baik disetujui atau ditolak</p>
        </div>

        {historyRequests.length === 0 ? (
          <p className="text-xs text-slate-400 italic bg-gray-50 p-4 rounded-xl border border-gray-100">Belum ada riwayat verifikasi yang diproses.</p>
        ) : (
          <div className="bg-white border border-slate-200 rounded-2xl overflow-hidden shadow-sm">
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-slate-200">
                <thead className="bg-slate-50/50">
                  <tr>
                    <th scope="col" className="px-6 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-widest">Siswa & Kelas</th>
                    <th scope="col" className="px-6 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-widest">Detail Waktu</th>
                    <th scope="col" className="px-6 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-widest">Alasan</th>
                    <th scope="col" className="px-6 py-3 text-left text-[10px] font-bold text-slate-400 uppercase tracking-widest">Keputusan Anda</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-200/60 text-xs">
                  {historyRequests.map(p => (
                    <tr key={p.id} className="hover:bg-slate-50/50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <p className="font-bold text-slate-900">{p.siswaName}</p>
                        <p className="text-[10px] text-slate-500 font-medium">Kelas {p.siswaClass} | NISN: {p.siswaInduk}</p>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <p className="font-semibold text-slate-800">{p.day}, {formatIndonesianDate(p.date)}</p>
                        <p className="text-[10px] font-mono text-slate-400">Jam: {p.timeExitProposed} - {p.timeReturnProposed || "Selesai"}</p>
                      </td>
                      <td className="px-6 py-4">
                        <p className="italic max-w-[200px] truncate font-sans">"{p.reason}"</p>
                        {p.statusMapel === "rejected" && p.rejectReason && (
                          <span className="text-[10px] text-rose-800 font-semibold block mt-1 bg-rose-50 p-1 rounded">Ket: {p.rejectReason}</span>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border ${getStatusStyle(p.statusMapel)}`}>
                          {p.statusMapel === "approved" ? "Selesai Disetujui" : "Ditolak Guru Mapel"}
                        </span>
                        {p.timeApprovedMapel && (
                          <span className="block text-[9px] text-slate-400 font-mono mt-0.5">Jam: {p.timeApprovedMapel}</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </section>
    </div>
  );
}
