import React, { useState } from 'react';
import { Proposal, OutputItem, UserRole } from '../types';
import { formatRupiah, getProposalStatusBadge } from '../data/storage';
import {
  Award,
  BookOpen,
  CheckCircle2,
  Clock,
  ExternalLink,
  FileCheck,
  FileText,
  Filter,
  Layers,
  Plus,
  Search,
  ShieldCheck,
  Sparkles,
  TrendingUp,
  Upload
} from 'lucide-react';

interface MonevLuaranViewProps {
  proposals: Proposal[];
  userRole: UserRole;
  onSelectProposal: (proposal: Proposal) => void;
  onOpenReportModal: (proposal: Proposal) => void;
  onVerifyOutput: (proposalId: string, outputId: string) => void;
}

export const MonevLuaranView: React.FC<MonevLuaranViewProps> = ({
  proposals,
  userRole,
  onSelectProposal,
  onOpenReportModal,
  onVerifyOutput,
}) => {
  const [activeTab, setActiveTab] = useState<'luaran' | 'monev_proposals'>('luaran');
  const [selectedType, setSelectedType] = useState<string>('ALL');
  const [searchQuery, setSearchQuery] = useState('');

  // Collect all outputs across all proposals
  const allOutputs = proposals.flatMap((p) =>
    p.actualOutputs.map((out) => ({
      ...out,
      proposalId: p.id,
      proposalCode: p.code,
      proposalTitle: p.title,
      leaderName: p.leader.name,
      department: p.leader.department,
      faculty: p.leader.faculty,
      programType: p.type,
    }))
  );

  // Filtered outputs
  const filteredOutputs = allOutputs.filter((item) => {
    if (selectedType !== 'ALL' && !item.type.includes(selectedType)) return false;
    if (searchQuery.trim()) {
      const q = searchQuery.toLowerCase();
      const matchTitle = item.title.toLowerCase().includes(q);
      const matchAuthor = item.leaderName.toLowerCase().includes(q);
      const matchVenue = item.venueOrPublisher.toLowerCase().includes(q);
      const matchCode = item.proposalCode.toLowerCase().includes(q);
      if (!matchTitle && !matchAuthor && !matchVenue && !matchCode) return false;
    }
    return true;
  });

  // Proposals needing monev or final reports
  const fundedProposals = proposals.filter((p) =>
    ['APPROVED', 'PROGRESS_REPORTED', 'FINAL_REPORTED', 'COMPLETED'].includes(p.status)
  );

  return (
    <div className="space-y-6">
      {/* Top Banner */}
      <div className="bg-white rounded-xl p-6 border border-slate-200 shadow-xs flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <span className="w-8 h-8 rounded-lg bg-indigo-600 flex items-center justify-center text-white">
              <Award className="w-5 h-5" />
            </span>
            <h1 className="text-xl font-bold text-slate-900">
              Monitoring, Evaluasi (Monev) & Repositori Luaran LPPM
            </h1>
          </div>
          <p className="text-xs text-slate-500 max-w-2xl">
            Pendokumentasian laporan kemajuan 70%, laporan akhir 100%, serta validasi capaian luaran publikasi ilmiah bereputasi, HKI, paten, dan teknologi tepat guna.
          </p>
        </div>

        {/* Tab switcher: Repositori Luaran vs Monev Berjalan */}
        <div className="flex items-center bg-slate-100 p-1 rounded-xl border border-slate-200 text-xs">
          <button
            onClick={() => setActiveTab('luaran')}
            className={`px-3 py-1.5 rounded-lg font-medium transition-all cursor-pointer flex items-center gap-1.5 ${
              activeTab === 'luaran'
                ? 'bg-white text-indigo-900 shadow-xs font-bold'
                : 'text-slate-600 hover:text-slate-900'
            }`}
          >
            <Award className="w-4 h-4 text-indigo-600" />
            Repositori Luaran ({allOutputs.length})
          </button>
          <button
            onClick={() => setActiveTab('monev_proposals')}
            className={`px-3 py-1.5 rounded-lg font-medium transition-all cursor-pointer flex items-center gap-1.5 ${
              activeTab === 'monev_proposals'
                ? 'bg-white text-indigo-900 shadow-xs font-bold'
                : 'text-slate-600 hover:text-slate-900'
            }`}
          >
            <Clock className="w-4 h-4 text-emerald-600" />
            Progres Monev Hibah ({fundedProposals.length})
          </button>
        </div>
      </div>

      {/* VIEW 1: REPOSITORI LUARAN */}
      {activeTab === 'luaran' && (
        <div className="space-y-4">
          {/* Quick Metrics of Outputs */}
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs">
              <span className="text-[10px] uppercase font-bold text-slate-500 block">Jurnal Scopus / Q1-Q4</span>
              <div className="text-2xl font-black text-slate-900 mt-1">
                {allOutputs.filter((o) => o.type.includes('Scopus')).length} Artikel
              </div>
              <div className="text-[11px] text-blue-600 font-medium mt-0.5">Bereputasi Internasional</div>
            </div>

            <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs">
              <span className="text-[10px] uppercase font-bold text-slate-500 block">Jurnal SINTA 1-4</span>
              <div className="text-2xl font-black text-slate-900 mt-1">
                {allOutputs.filter((o) => o.type.includes('SINTA')).length} Artikel
              </div>
              <div className="text-[11px] text-emerald-600 font-medium mt-0.5">Akreditasi Nasional</div>
            </div>

            <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs">
              <span className="text-[10px] uppercase font-bold text-slate-500 block">Hak Cipta & Paten HKI</span>
              <div className="text-2xl font-black text-slate-900 mt-1">
                {allOutputs.filter((o) => o.type.includes('HKI') || o.type.includes('Paten')).length} Berkas
              </div>
              <div className="text-[11px] text-amber-600 font-medium mt-0.5">DJKI Kemenkumham</div>
            </div>

            <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs">
              <span className="text-[10px] uppercase font-bold text-slate-500 block">Buku & TTG Mitra</span>
              <div className="text-2xl font-black text-slate-900 mt-1">
                {allOutputs.filter((o) => o.type.includes('Buku') || o.type.includes('Prototipe')).length} Unit
              </div>
              <div className="text-[11px] text-indigo-600 font-medium mt-0.5">Hilirisasi Riset</div>
            </div>
          </div>

          {/* Search and Category Filters */}
          <div className="bg-white p-4 rounded-xl border border-slate-200 shadow-xs flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-3 text-xs">
            <div className="relative flex-1">
              <Search className="w-4 h-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                placeholder="Cari judul artikel, nama jurnal, penulis, atau nomor sertifikat..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-9 pr-4 py-2 bg-slate-50 border border-slate-200 rounded-lg"
              />
            </div>

            <div className="flex items-center gap-2">
              <select
                value={selectedType}
                onChange={(e) => setSelectedType(e.target.value)}
                className="bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-slate-700"
              >
                <option value="ALL">Semua Kategori Luaran</option>
                <option value="Scopus">Jurnal Scopus</option>
                <option value="SINTA">Jurnal SINTA</option>
                <option value="HKI">Hak Cipta / Paten</option>
                <option value="Buku">Buku Ber-ISBN</option>
                <option value="Prototipe">Prototipe / TTG</option>
              </select>
            </div>
          </div>

          {/* Outputs List */}
          {filteredOutputs.length === 0 ? (
            <div className="bg-white rounded-xl border border-dashed border-slate-300 p-8 text-center text-xs">
              <Award className="w-8 h-8 text-slate-400 mx-auto mb-2" />
              <div className="font-semibold text-slate-800">Tidak ada bukti luaran yang ditemukan</div>
              <p className="text-slate-500 text-[11px] mt-1">Gunakan tab "Progres Monev Hibah" untuk merekam luaran dari usulan yang didanai.</p>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {filteredOutputs.map((item) => (
                <div
                  key={item.id}
                  className="bg-white border border-slate-200 rounded-xl p-4 shadow-xs flex flex-col justify-between space-y-3"
                >
                  <div className="space-y-2">
                    <div className="flex items-center justify-between gap-2 flex-wrap">
                      <span className="bg-indigo-50 text-indigo-800 border border-indigo-200 font-bold text-[10px] px-2 py-0.5 rounded">
                        {item.type}
                      </span>
                      {item.verifiedByLppm ? (
                        <span className="bg-emerald-50 text-emerald-800 border border-emerald-200 font-bold text-[10px] px-2 py-0.5 rounded flex items-center gap-1">
                          <CheckCircle2 className="w-3 h-3 text-emerald-600" /> Tervalidasi LPPM
                        </span>
                      ) : (
                        <span className="bg-amber-50 text-amber-800 border border-amber-200 font-bold text-[10px] px-2 py-0.5 rounded flex items-center gap-1">
                          <Clock className="w-3 h-3" /> Menunggu Validasi
                        </span>
                      )}
                    </div>

                    <h4 className="font-bold text-slate-900 text-sm leading-snug">{item.title}</h4>

                    <div className="text-slate-600 text-xs space-y-1">
                      <div>
                        <span className="text-slate-400">Penerbit / Jurnal:</span>{' '}
                        <span className="font-medium text-slate-800">{item.venueOrPublisher}</span> ({item.year})
                      </div>
                      <div>
                        <span className="text-slate-400">Penulis:</span>{' '}
                        <span className="font-medium text-slate-800">{item.leaderName}</span> ({item.department})
                      </div>
                      <div className="text-slate-500 font-mono text-[10px]">
                        Asal Riset: {item.proposalCode}
                      </div>
                    </div>

                    {item.certificateNo && (
                      <div className="bg-slate-50 p-2 rounded-md font-mono text-[11px] text-slate-700">
                        Nomor Registrasi / HKI: <b>{item.certificateNo}</b>
                      </div>
                    )}
                  </div>

                  <div className="pt-3 border-t border-slate-100 flex items-center justify-between text-xs">
                    {item.urlOrDoi ? (
                      <a
                        href={item.urlOrDoi}
                        target="_blank"
                        rel="noreferrer"
                        className="text-blue-600 font-semibold flex items-center gap-1 hover:underline"
                      >
                        <ExternalLink className="w-3.5 h-3.5" /> Buka DOI / Tautan
                      </a>
                    ) : (
                      <span className="text-slate-400 text-[11px]">Berkas Dokumen Tersimpan</span>
                    )}

                    {userRole === 'admin_lppm' && !item.verifiedByLppm && (
                      <button
                        onClick={() => onVerifyOutput(item.proposalId, item.id)}
                        className="bg-emerald-600 hover:bg-emerald-700 text-white font-semibold px-2.5 py-1 rounded text-xs cursor-pointer"
                      >
                        Validasi LPPM
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* VIEW 2: MONEV & PROGRES HIBAH PROPOSALS */}
      {activeTab === 'monev_proposals' && (
        <div className="space-y-4">
          <div className="bg-blue-50/60 border border-blue-200 p-4 rounded-xl text-xs text-blue-950 flex items-start gap-3">
            <Clock className="w-5 h-5 text-blue-700 shrink-0 mt-0.5" />
            <div>
              <span className="font-bold block text-sm">Ketentuan Pelaporan Monitoring & Evaluasi (Monev):</span>
              <p className="text-slate-600 mt-1 leading-relaxed">
                Penerima pendanaan wajib mengunggah Laporan Kemajuan 70% dan Catatan Harian Riset (Logbook) sebelum pencairan termin kedua. Laporan akhir 100% dan bukti luaran wajib disertakan sebelum penutupan tahun anggaran.
              </p>
            </div>
          </div>

          <div className="bg-white rounded-xl border border-slate-200 overflow-hidden shadow-xs">
            <table className="w-full text-left text-xs">
              <thead className="bg-slate-50 border-b border-slate-200 text-slate-600 font-semibold uppercase text-[10px]">
                <tr>
                  <th className="py-3 px-4">Usulan & Ketua</th>
                  <th className="py-3 px-4">Pagu Kontrak</th>
                  <th className="py-3 px-4">Laporan Kemajuan (70%)</th>
                  <th className="py-3 px-4">Laporan Akhir (100%)</th>
                  <th className="py-3 px-4">Luaran Tercatat</th>
                  <th className="py-3 px-4 text-right">Aksi</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200 text-slate-700">
                {fundedProposals.map((prop) => {
                  const badge = getProposalStatusBadge(prop.status);
                  return (
                    <tr key={prop.id} className="hover:bg-slate-50 transition-colors">
                      <td className="py-3.5 px-4 max-w-xs">
                        <div className="font-mono text-[10px] text-slate-500 mb-0.5">{prop.code}</div>
                        <div className="font-semibold text-slate-900 line-clamp-1">{prop.title}</div>
                        <div className="text-[11px] text-slate-500 mt-0.5">
                          {prop.leader.name} ({prop.leader.department})
                        </div>
                      </td>

                      <td className="py-3.5 px-4 whitespace-nowrap font-bold text-slate-900 font-mono">
                        {formatRupiah(prop.approvedBudget || prop.requestedBudget)}
                      </td>

                      <td className="py-3.5 px-4 whitespace-nowrap">
                        {prop.progressReport ? (
                          <div className="space-y-0.5">
                            <span className="bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded font-bold text-[10px] flex items-center gap-1 w-fit">
                              <CheckCircle2 className="w-3 h-3" /> {prop.progressReport.progressPercent}% Capaian
                            </span>
                            <div className="text-[10px] text-slate-500 font-mono">
                              Realisasi: {formatRupiah(prop.progressReport.fundExpended)}
                            </div>
                          </div>
                        ) : (
                          <span className="text-amber-700 bg-amber-50 border border-amber-200 px-2 py-0.5 rounded text-[10px] font-medium">
                            Belum Diunggah
                          </span>
                        )}
                      </td>

                      <td className="py-3.5 px-4 whitespace-nowrap">
                        {prop.finalReport ? (
                          <span className="bg-emerald-100 text-emerald-800 px-2 py-0.5 rounded font-bold text-[10px] flex items-center gap-1 w-fit">
                            <CheckCircle2 className="w-3 h-3" /> Selesai 100%
                          </span>
                        ) : (
                          <span className="text-slate-400 text-[10px]">Menunggu Jadwal</span>
                        )}
                      </td>

                      <td className="py-3.5 px-4 whitespace-nowrap">
                        <span className="font-bold text-indigo-700 bg-indigo-50 px-2 py-0.5 rounded text-xs">
                          {prop.actualOutputs.length} Luaran
                        </span>
                      </td>

                      <td className="py-3.5 px-4 text-right whitespace-nowrap">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => onOpenReportModal(prop)}
                            className="bg-blue-50 text-blue-700 hover:bg-blue-100 font-semibold px-2.5 py-1 rounded text-xs transition-colors cursor-pointer"
                          >
                            Update Monev
                          </button>
                          <button
                            onClick={() => onSelectProposal(prop)}
                            className="text-slate-600 hover:text-slate-900 font-medium px-2 py-1 rounded hover:bg-slate-100 text-xs cursor-pointer"
                          >
                            Detail
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};
