'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { PageHeader } from '@/components/common/PageHeader';
import { StatusBadge } from '@/components/common/StatusBadge';
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
import { toast } from '@/lib/stores/notificationStore';
import { 
  Search, 
  Edit3, 
  Trash2, 
  Building2, 
  Loader2
} from 'lucide-react';
import axios from 'axios';

interface PTItem {
  id: string;
  code: string;
  name: string;
  city: string;
}

interface LaporanInstitusiItem {
  id: string;
  tahun: string;
  perguruan_tinggi_id: string;
  pt_code: string;
  pt_name: string;
  status: 'draft' | 'menunggu_verifikasi' | 'terverifikasi' | 'ditolak';
  kelengkapan: string;
  checklist_data: string; // JSON string
  updated_at: string;
}

export default function InstitusiPage() {
  const router = useRouter();
  const [reports, setReports] = useState<LaporanInstitusiItem[]>([]);
  const [pts, setPts] = useState<PTItem[]>([]);
  const [loading, setLoading] = useState(true);

  // Filters
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedYearFilter, setSelectedYearFilter] = useState('Semua');

  // Modal states
  const [isConfirmOpen, setIsConfirmOpen] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);

  const fetchReportsAndPTs = async () => {
    setLoading(true);
    try {
      const [reportsRes, ptsRes] = await Promise.all([
        axios.get('/api/institusi'),
        axios.get('/api/institusi?action=pts')
      ]);

      if (reportsRes.data.success) {
        setReports(reportsRes.data.data);
      }
      if (ptsRes.data.success) {
        setPts(ptsRes.data.data);
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      toast.error('Gagal mengambil data dari server');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchReportsAndPTs();
  }, []);

  const handleOpenEdit = (item: LaporanInstitusiItem) => {
    router.push(`/dashboard/admin/institusi/create?id=${item.id}`);
  };

  const handleDelete = async () => {
    if (!deleteTargetId) return;

    try {
      const res = await axios.delete(`/api/institusi?id=${deleteTargetId}`);
      if (res.data.success) {
        toast.success('Laporan institusi berhasil dihapus.');
        fetchReportsAndPTs();
      } else {
        toast.error(res.data.message || 'Gagal menghapus laporan.');
      }
    } catch (error) {
      console.error(error);
      toast.error('Gagal menghapus laporan.');
    }
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return '-';
    const date = new Date(dateString);
    return date.toLocaleDateString('id-ID', {
      day: 'numeric',
      month: 'short',
      year: 'numeric'
    });
  };

  // Filter lists based on search & year select
  const filteredReports = reports.filter(item => {
    const matchesSearch = 
      item.pt_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.pt_code.toLowerCase().includes(searchQuery.toLowerCase()) ||
      item.tahun.includes(searchQuery);

    const matchesYear = selectedYearFilter === 'Semua' ? true : item.tahun === selectedYearFilter;
    
    return matchesSearch && matchesYear;
  });

  // Pagination states
  const [currentPage, setCurrentPage] = useState(1);
  const [rowsPerPage, setRowsPerPage] = useState<number | 'all'>(10);

  // Reset pagination when filter changes
  useEffect(() => {
    setCurrentPage(1);
  }, [searchQuery, selectedYearFilter]);

  const totalRows = filteredReports.length;
  const totalPages = rowsPerPage === 'all' ? 1 : Math.ceil(totalRows / rowsPerPage);
  const startIndex = (currentPage - 1) * (rowsPerPage === 'all' ? 0 : rowsPerPage);
  const endIndex = rowsPerPage === 'all' ? totalRows : Math.min(startIndex + rowsPerPage, totalRows);
  const paginatedReports = filteredReports.slice(startIndex, endIndex);

  return (
    <div className="space-y-6">
      {/* Page Header */}
      <PageHeader
        title="Institusi"
        description="Pelaporan tahunan institusi berdasarkan checklist panduan SIMKATMAWA."
      />

      {/* Styled Banner matching screenshot */}
      <div className="bg-[#EBF3FF] border border-[#D5E6FF] rounded-2xl p-6 flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div className="space-y-2">
          <span className="inline-flex items-center px-3 py-1 bg-[#D2E4FF] text-[#1E4ED8] text-xs font-semibold rounded-full">
            Tata Kelola
          </span>
          <h2 className="text-xl font-bold text-slate-800">
            Manajemen Kelembagaan / Institusi
          </h2>
        </div>

        {/* Filters Panel in Banner */}
        <div className="flex items-center gap-2.5 w-full md:w-auto">
          <div className="relative flex-1 md:flex-initial">
            <span className="absolute inset-y-0 left-0 pl-3 flex items-center text-slate-400 pointer-events-none">
              <Search className="h-4 w-4" />
            </span>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="Cari PT, kode PT, atau tahun"
              className="w-full md:w-64 pl-9 pr-4 py-2 bg-white border border-slate-200 rounded-xl text-sm placeholder:text-slate-400 text-slate-800 font-medium focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all shadow-sm"
            />
          </div>
          <select
            value={selectedYearFilter}
            onChange={(e) => setSelectedYearFilter(e.target.value)}
            className="px-4 py-2 bg-white border border-slate-200 rounded-xl text-sm text-slate-700 font-medium focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all shadow-sm"
          >
            <option value="Semua">Semua Tahun</option>
            <option value="2026">2026</option>
            <option value="2025">2025</option>
            <option value="2024">2024</option>
            <option value="2023">2023</option>
          </select>
          <button
            onClick={() => fetchReportsAndPTs()}
            className="p-2.5 bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 rounded-xl transition-all shadow-sm flex items-center justify-center cursor-pointer"
            title="Refresh"
          >
            <Search className="h-4 w-4 text-slate-500" />
          </button>
        </div>
      </div>

      {/* Main Table Card */}
      <div className="bg-white border border-slate-100 rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.02)] overflow-hidden">
        {/* Card Header */}
        <div className="p-6 border-b border-slate-100 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
          <h3 className="text-lg font-bold text-slate-800">
            Daftar Institusi
          </h3>
          <div className="flex flex-wrap items-center gap-4 w-full sm:w-auto justify-between sm:justify-end">
            <div className="flex items-center gap-2 text-xs font-semibold text-slate-500">
              <span>Tampilkan</span>
              <select
                value={rowsPerPage}
                onChange={(e) => {
                  const val = e.target.value;
                  setRowsPerPage(val === 'all' ? 'all' : parseInt(val));
                  setCurrentPage(1);
                }}
                className="px-2.5 py-1.5 bg-white border border-slate-200 rounded-lg text-slate-700 font-bold focus:outline-none focus:border-primary transition-all shadow-sm"
              >
                <option value={10}>10</option>
                <option value={25}>25</option>
                <option value={50}>50</option>
                <option value="all">Semua</option>
              </select>
              <span>baris per halaman</span>
            </div>
            <Link
              href="/dashboard/admin/institusi/create"
              className="bg-[#0B1936] hover:bg-[#12254B] text-white rounded-xl px-5 py-2.5 text-xs font-bold flex items-center gap-2 shadow-lg shadow-slate-900/10 hover:shadow-slate-900/25 transition-all duration-200 cursor-pointer"
            >
              + Tambah Laporan
            </Link>
          </div>
        </div>

        {/* Table Body */}
        <div className="overflow-x-auto">
          <table className="w-full border-collapse text-left">
            <thead>
              <tr className="bg-slate-50/50 border-b border-slate-100">
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">ID</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">Tahun</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">Kode PT</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">Perguruan Tinggi</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">Status</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">Kelengkapan</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider">Diperbarui</th>
                <th className="px-6 py-4 text-xs font-bold text-slate-600 uppercase tracking-wider text-center">Aksi</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100/70">
              {loading ? (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-slate-500 font-medium">
                    <div className="flex flex-col items-center justify-center gap-2">
                      <Loader2 className="h-8 w-8 animate-spin text-primary" />
                      <span>Memuat data laporan institusi...</span>
                    </div>
                  </td>
                </tr>
              ) : paginatedReports.length > 0 ? (
                paginatedReports.map((item) => (
                  <tr key={item.id} className="hover:bg-slate-50/50 transition-colors align-middle">
                    <td className="px-6 py-4 text-sm font-semibold text-slate-400">
                      {item.id}
                    </td>
                    <td className="px-6 py-4 text-sm font-extrabold text-slate-700">
                      {item.tahun}
                    </td>
                    <td className="px-6 py-4 text-sm font-semibold text-slate-600">
                      {item.pt_code}
                    </td>
                    <td className="px-6 py-4 text-sm font-bold text-slate-800">
                      {item.pt_name}
                    </td>
                    <td className="px-6 py-4 text-sm">
                      <StatusBadge status={item.status} />
                    </td>
                    <td className="px-6 py-4 text-sm">
                      <div className="flex flex-col gap-1 w-28">
                        <span className="font-bold text-slate-600">
                          {item.kelengkapan}
                        </span>
                        {/* Custom visual progress bar */}
                        <div className="w-full bg-slate-100 rounded-full h-1.5 overflow-hidden">
                          <div 
                            className="bg-primary h-1.5 rounded-full" 
                            style={{ 
                              width: `${Math.round((parseInt(item.kelengkapan.split('/')[0]) / parseInt(item.kelengkapan.split('/')[1] || '10')) * 100)}%` 
                            }}
                          />
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 text-sm font-medium text-slate-500">
                      {formatDate(item.updated_at)}
                    </td>
                    <td className="px-6 py-4 text-sm text-center">
                      <div className="flex items-center justify-center gap-2">
                        <button
                          onClick={() => handleOpenEdit(item)}
                          className="p-1.5 bg-transparent text-slate-400 hover:bg-primary/10 hover:text-primary rounded-lg transition-all"
                          title="Edit Laporan"
                        >
                          <Edit3 className="h-4 w-4" />
                        </button>
                        <button
                          onClick={() => {
                            setDeleteTargetId(item.id);
                            setIsConfirmOpen(true);
                          }}
                          className="p-1.5 bg-transparent text-slate-400 hover:bg-danger/10 hover:text-danger rounded-lg transition-all"
                          title="Hapus Laporan"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              ) : (
                <tr>
                  <td colSpan={8} className="px-6 py-12 text-center text-slate-400 font-medium">
                    Belum ada laporan institusi yang cocok.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination Footer */}
        <div className="p-4 border-t border-slate-100 flex flex-col sm:flex-row items-center justify-between gap-4 text-xs font-semibold text-slate-500 bg-slate-50/50">
          <span>
            Menampilkan {totalRows > 0 ? startIndex + 1 : 0} - {endIndex} dari {totalRows} data
          </span>
          
          {totalPages > 1 && (
              <div className="flex items-center gap-1.5">
                <button
                  type="button"
                  disabled={currentPage === 1}
                  onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
                  className="p-1.5 bg-white hover:bg-slate-50 border border-slate-200 rounded-lg text-slate-600 font-bold transition-all disabled:opacity-50"
                >
                  Sebelumnya
                </button>
                {Array.from({ length: totalPages }, (_, i) => i + 1).map(pageNum => (
                  <button
                    key={pageNum}
                    type="button"
                    onClick={() => setCurrentPage(pageNum)}
                    className={`w-7 h-7 rounded-lg text-xs font-bold transition-all ${
                      currentPage === pageNum
                        ? "bg-[#0B1936] text-white"
                        : "bg-white hover:bg-slate-50 border border-slate-200 text-slate-600"
                    }`}
                  >
                    {pageNum}
                  </button>
                ))}
                <button
                  type="button"
                  disabled={currentPage === totalPages}
                  onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
                  className="p-1.5 bg-white hover:bg-slate-50 border border-slate-200 rounded-lg text-slate-600 font-bold transition-all disabled:opacity-50"
                >
                  Selanjutnya
                </button>
              </div>
            )}
        </div>
      </div>



      {/* Delete Confirmation Dialog */}
      <ConfirmDialog
        isOpen={isConfirmOpen}
        onClose={() => {
          setIsConfirmOpen(false);
          setDeleteTargetId(null);
        }}
        onConfirm={handleDelete}
        title="Hapus Laporan Institusi?"
        description="Apakah Anda yakin ingin menghapus laporan institusi ini? Tindakan ini tidak dapat dibatalkan."
        isDestructive
        confirmLabel="Hapus"
        cancelLabel="Batal"
      />
    </div>
  );
}
