import React, { useState } from 'react';
import { Proposal, OutputItem, ProgressReport, FinalReport } from '../types';
import { formatRupiah } from '../data/storage';
import {
  X,
  FileCheck,
  Award,
  Upload,
  CheckCircle2,
  DollarSign,
  Layers,
  BookOpen
} from 'lucide-react';

interface ReportModalProps {
  proposal: Proposal;
  onClose: () => void;
  onSaveProgressReport: (proposalId: string, report: ProgressReport) => void;
  onSaveFinalReport: (proposalId: string, report: FinalReport) => void;
  onAddOutput: (proposalId: string, output: OutputItem) => void;
}

export const ReportModal: React.FC<ReportModalProps> = ({
  proposal,
  onClose,
  onSaveProgressReport,
  onSaveFinalReport,
  onAddOutput,
}) => {
  const [activeTab, setActiveTab] = useState<'progress' | 'final' | 'add_output'>('progress');

  // Progress state
  const [progressPercent, setProgressPercent] = useState<number>(
    proposal.progressReport?.progressPercent || 70
  );
  const [progressSummary, setProgressSummary] = useState<string>(
    proposal.progressReport?.summary ||
      'Telah dilaksanakan pengumpulan data lapangan, analisis sampel pendahuluan, dan draft manuskrip publikasi.'
  );
  const [progressFund, setProgressFund] = useState<number>(
    proposal.progressReport?.fundExpended || Math.round((proposal.approvedBudget || proposal.requestedBudget) * 0.7)
  );
  const [progressDocName, setProgressDocName] = useState<string>(
    proposal.progressReport?.documentName || `Laporan_Kemajuan_${proposal.code}.pdf`
  );

  // Final report state
  const [finalSummary, setFinalSummary] = useState<string>(
    proposal.finalReport?.executiveSummary ||
      'Seluruh target tahapan penelitian dan pengabdian telah diselesaikan 100%. Luaran publikasi telah terbit dan laporan keuangan tersusun lengkap.'
  );
  const [finalFund, setFinalFund] = useState<number>(
    proposal.finalReport?.fundExpended || proposal.approvedBudget || proposal.requestedBudget
  );
  const [finalDocName, setFinalDocName] = useState<string>(
    proposal.finalReport?.documentName || `Laporan_Akhir_${proposal.code}.pdf`
  );

  // New Output state
  const [outputType, setOutputType] = useState<OutputItem['type']>('Jurnal Nasional Terakreditasi (SINTA 1-4)');
  const [outputTitle, setOutputTitle] = useState('');
  const [outputVenue, setOutputVenue] = useState('');
  const [outputYear, setOutputYear] = useState<number>(2025);
  const [outputStatus, setOutputStatus] = useState<OutputItem['status']>('Published / Terbit');
  const [outputDoi, setOutputDoi] = useState('');
  const [outputCertNo, setOutputCertNo] = useState('');

  const handleSaveProgress = (e: React.FormEvent) => {
    e.preventDefault();
    const report: ProgressReport = {
      submittedAt: new Date().toISOString().split('T')[0],
      progressPercent: Number(progressPercent),
      summary: progressSummary,
      fundExpended: Number(progressFund),
      documentName: progressDocName,
      status: 'Disetujui LPPM',
      feedback: 'Laporan kemajuan diterima dan diverifikasi sesuai ketentuan.',
    };
    onSaveProgressReport(proposal.id, report);
    onClose();
  };

  const handleSaveFinal = (e: React.FormEvent) => {
    e.preventDefault();
    const report: FinalReport = {
      submittedAt: new Date().toISOString().split('T')[0],
      executiveSummary: finalSummary,
      fundExpended: Number(finalFund),
      documentName: finalDocName,
      status: 'Disetujui LPPM',
      feedback: 'Laporan akhir disetujui, luaran lengkap.',
    };
    onSaveFinalReport(proposal.id, report);
    onClose();
  };

  const handleSaveOutput = (e: React.FormEvent) => {
    e.preventDefault();
    if (!outputTitle.trim()) {
      alert('Judul luaran wajib diisi!');
      return;
    }

    const newOut: OutputItem = {
      id: `out-${Date.now()}`,
      type: outputType,
      title: outputTitle,
      venueOrPublisher: outputVenue || 'Jurnal LPPM Kampus',
      year: Number(outputYear),
      status: outputStatus,
      urlOrDoi: outputDoi,
      certificateNo: outputCertNo,
      verifiedByLppm: true,
      verifiedAt: new Date().toISOString().split('T')[0],
    };
    onAddOutput(proposal.id, newOut);
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-3 sm:p-4">
      <div className="bg-white rounded-2xl shadow-2xl border border-slate-200 w-full max-w-2xl max-h-[92vh] flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200">
        {/* Header */}
        <div className="px-6 py-4 bg-slate-900 text-white flex items-center justify-between">
          <div>
            <h2 className="text-base font-bold text-white">Pelaporan Monev & Pencatatan Luaran</h2>
            <p className="text-xs text-slate-300 line-clamp-1">{proposal.code}: {proposal.title}</p>
          </div>

          <button
            onClick={onClose}
            className="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white transition-colors cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Tab switch */}
        <div className="bg-slate-50 border-b border-slate-200 px-6 flex items-center gap-2 text-xs">
          <button
            onClick={() => setActiveTab('progress')}
            className={`py-3 px-3 font-semibold border-b-2 cursor-pointer transition-colors ${
              activeTab === 'progress'
                ? 'border-blue-600 text-blue-700'
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            1. Laporan Kemajuan (70%)
          </button>

          <button
            onClick={() => setActiveTab('final')}
            className={`py-3 px-3 font-semibold border-b-2 cursor-pointer transition-colors ${
              activeTab === 'final'
                ? 'border-blue-600 text-blue-700'
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            2. Laporan Akhir (100%)
          </button>

          <button
            onClick={() => setActiveTab('add_output')}
            className={`py-3 px-3 font-semibold border-b-2 cursor-pointer transition-colors ${
              activeTab === 'add_output'
                ? 'border-blue-600 text-blue-700'
                : 'border-transparent text-slate-600 hover:text-slate-900'
            }`}
          >
            3. Rekam Bukti Luaran Riset
          </button>
        </div>

        {/* Form Body */}
        <div className="p-6 overflow-y-auto flex-1 text-xs">
          {/* TAB 1: PROGRESS REPORT */}
          {activeTab === 'progress' && (
            <form onSubmit={handleSaveProgress} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block font-bold text-slate-800 mb-1">Persentase Capaian Fisik (%):</label>
                  <input
                    type="number"
                    min="1"
                    max="100"
                    value={progressPercent}
                    onChange={(e) => setProgressPercent(Number(e.target.value))}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                    required
                  />
                </div>

                <div>
                  <label className="block font-bold text-slate-800 mb-1">Realisasi Dana Terserap (Rp):</label>
                  <input
                    type="number"
                    value={progressFund}
                    onChange={(e) => setProgressFund(Number(e.target.value))}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg font-mono text-slate-900"
                    required
                  />
                </div>
              </div>

              <div>
                <label className="block font-bold text-slate-800 mb-1">
                  Ringkasan Kemajuan Pelaksanaan & Logbook:
                </label>
                <textarea
                  rows={4}
                  value={progressSummary}
                  onChange={(e) => setProgressSummary(e.target.value)}
                  className="w-full p-2.5 bg-slate-50 border border-slate-300 rounded-lg leading-relaxed text-slate-900"
                  required
                />
              </div>

              <div>
                <label className="block font-bold text-slate-800 mb-1">Nama Dokumen Laporan Kemajuan:</label>
                <input
                  type="text"
                  value={progressDocName}
                  onChange={(e) => setProgressDocName(e.target.value)}
                  className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg font-mono text-slate-900"
                />
              </div>

              <div className="pt-2 flex justify-end">
                <button
                  type="submit"
                  className="bg-blue-600 hover:bg-blue-700 text-white font-bold px-4 py-2 rounded-lg cursor-pointer"
                >
                  Simpan Laporan Kemajuan 70%
                </button>
              </div>
            </form>
          )}

          {/* TAB 2: FINAL REPORT */}
          {activeTab === 'final' && (
            <form onSubmit={handleSaveFinal} className="space-y-4">
              <div>
                <label className="block font-bold text-slate-800 mb-1">Total Realisasi Anggaran Akhir (Rp):</label>
                <input
                  type="number"
                  value={finalFund}
                  onChange={(e) => setFinalFund(Number(e.target.value))}
                  className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg font-mono text-slate-900"
                  required
                />
              </div>

              <div>
                <label className="block font-bold text-slate-800 mb-1">Ringkasan Eksekutif Hasil Kegiatan 100%:</label>
                <textarea
                  rows={5}
                  value={finalSummary}
                  onChange={(e) => setFinalSummary(e.target.value)}
                  className="w-full p-2.5 bg-slate-50 border border-slate-300 rounded-lg leading-relaxed text-slate-900"
                  required
                />
              </div>

              <div>
                <label className="block font-bold text-slate-800 mb-1">Nama Dokumen Laporan Akhir (PDF):</label>
                <input
                  type="text"
                  value={finalDocName}
                  onChange={(e) => setFinalDocName(e.target.value)}
                  className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg font-mono text-slate-900"
                />
              </div>

              <div className="pt-2 flex justify-end">
                <button
                  type="submit"
                  className="bg-teal-600 hover:bg-teal-700 text-white font-bold px-4 py-2 rounded-lg cursor-pointer"
                >
                  Simpan Laporan Akhir 100%
                </button>
              </div>
            </form>
          )}

          {/* TAB 3: RECORD OUTPUT */}
          {activeTab === 'add_output' && (
            <form onSubmit={handleSaveOutput} className="space-y-4">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-bold text-slate-800 mb-1">Kategori Luaran:</label>
                  <select
                    value={outputType}
                    onChange={(e) => setOutputType(e.target.value as any)}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                  >
                    <option value="Jurnal Internasional Bereputasi (Scopus)">Jurnal Scopus Q1-Q4</option>
                    <option value="Jurnal Nasional Terakreditasi (SINTA 1-4)">Jurnal SINTA 1-4</option>
                    <option value="Hak Cipta / Paten HKI">Hak Cipta / Paten HKI</option>
                    <option value="Buku Ajar / Monograf Ber-ISBN">Buku Monograf Ber-ISBN</option>
                    <option value="Prototipe / TTG / Rekayasa Sosial">Prototipe / TTG Mitra</option>
                    <option value="Prosiding Seminar Internasional">Prosiding Seminar</option>
                  </select>
                </div>

                <div>
                  <label className="block font-bold text-slate-800 mb-1">Status Publikasi / Registrasi:</label>
                  <select
                    value={outputStatus}
                    onChange={(e) => setOutputStatus(e.target.value as any)}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                  >
                    <option value="Published / Terbit">Published / Terbit</option>
                    <option value="Accepted">Accepted (LoA)</option>
                    <option value="Granted / Sertifikat Terbit">Granted / Sertifikat Terbit</option>
                    <option value="Draft / Submitted">Draft / Submitted</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block font-bold text-slate-800 mb-1">Judul Artikel / Paten / Buku:</label>
                <input
                  type="text"
                  placeholder="Contoh: Implementasi Algoritma Deteksi Dini..."
                  value={outputTitle}
                  onChange={(e) => setOutputTitle(e.target.value)}
                  className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                  required
                />
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-bold text-slate-800 mb-1">Nama Jurnal / Penerbit / Lembaga:</label>
                  <input
                    type="text"
                    placeholder="Contoh: Jurnal Teknologi Komputer (SINTA 2)"
                    value={outputVenue}
                    onChange={(e) => setOutputVenue(e.target.value)}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                  />
                </div>

                <div>
                  <label className="block font-bold text-slate-800 mb-1">Tahun Terbit:</label>
                  <input
                    type="number"
                    value={outputYear}
                    onChange={(e) => setOutputYear(Number(e.target.value))}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                  />
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block font-bold text-slate-800 mb-1">Tautan URL / DOI:</label>
                  <input
                    type="url"
                    placeholder="https://doi.org/10.xxxx/..."
                    value={outputDoi}
                    onChange={(e) => setOutputDoi(e.target.value)}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg text-slate-900"
                  />
                </div>

                <div>
                  <label className="block font-bold text-slate-800 mb-1">Nomor Registrasi / HKI / ISBN:</label>
                  <input
                    type="text"
                    placeholder="EC002025xxx / ISBN 978-xxx"
                    value={outputCertNo}
                    onChange={(e) => setOutputCertNo(e.target.value)}
                    className="w-full p-2 bg-slate-50 border border-slate-300 rounded-lg font-mono text-slate-900"
                  />
                </div>
              </div>

              <div className="pt-2 flex justify-end">
                <button
                  type="submit"
                  className="bg-indigo-600 hover:bg-indigo-700 text-white font-bold px-4 py-2 rounded-lg cursor-pointer"
                >
                  Simpan Bukti Luaran ke Database
                </button>
              </div>
            </form>
          )}
        </div>
      </div>
    </div>
  );
};
