import React, { useState } from 'react';
import { Proposal, ReviewAssessment, ReviewCriterion } from '../types';
import { formatRupiah } from '../data/storage';
import {
  X,
  Award,
  CheckCircle2,
  AlertTriangle,
  FileText,
  Star,
  Sparkles,
  DollarSign
} from 'lucide-react';

interface ReviewModalProps {
  proposal: Proposal;
  onClose: () => void;
  onSubmitReview: (proposalId: string, review: ReviewAssessment) => void;
}

export const ReviewModal: React.FC<ReviewModalProps> = ({
  proposal,
  onClose,
  onSubmitReview,
}) => {
  const [reviewerName, setReviewerName] = useState('Prof. Dr. Ir. Budi Santoso, M.T.');
  const [reviewerNidn, setReviewerNidn] = useState('0015096503');

  const defaultCriteria: ReviewCriterion[] = [
    {
      id: 'c1',
      label: 'Urgensi & Relevansi Topik',
      description: 'Kesesuaian dengan Renstra LPPM, peta jalan riset, dan urgensi penyelesaian masalah',
      weight: 25,
      score: 4.5,
      notes: 'Topik sangat relevan dan mendesak untuk diselesaikan.',
    },
    {
      id: 'c2',
      label: 'Metodologi / Solusi Permasalahan',
      description: 'Ketajaman desain riset, kejelasan alur kerja, kesiapan teknologi tepat guna',
      weight: 30,
      score: 4,
      notes: 'Desain pengujian terstruktur dan metodis.',
    },
    {
      id: 'c3',
      label: 'Kompetensi & Rekam Jejak Tim',
      description: 'Kesesuaian keahlian ketua dan anggota, keterlibatan mahasiswa, rekam publikasi',
      weight: 15,
      score: 4.5,
      notes: 'Tim multidisiplin dengan rekam jejak memadai.',
    },
    {
      id: 'c4',
      label: 'Kewajaran Anggaran & Jadwal',
      description: 'Rasionalitas rincian biaya (SBM), kesesuaian pagu skema, dan timeline kerja',
      weight: 15,
      score: 4,
      notes: 'RAB cukup wajar, perlu sedikit penyesuaian belanja bahan.',
    },
    {
      id: 'c5',
      label: 'Potensi Capaian Luaran',
      description: 'Kualitas target jurnal terakreditasi/Scopus, sertifikat HKI/Paten, atau TTG',
      weight: 15,
      score: 4.5,
      notes: 'Target luaran wajib dan tambahan sangat menjanjikan.',
    },
  ];

  const [criteria, setCriteria] = useState<ReviewCriterion[]>(defaultCriteria);
  const [generalNotes, setGeneralNotes] = useState(
    'Usulan memenuhi standar mutu akademik LPPM. Disarankan penajaman pada uji coba skala lapangan dan percepatan pendaftaran HKI.'
  );

  // Calculate weighted score out of 100
  // Each score is out of 5. weightedScore = sum( (score/5) * weight )
  const totalScore = Math.round(
    criteria.reduce((acc, c) => acc + (c.score / 5) * c.weight, 0) * 10
  ) / 10;

  const [recommendation, setRecommendation] = useState<ReviewAssessment['recommendation']>(
    totalScore >= 85
      ? 'Lolos Tanpa Revisi'
      : totalScore >= 75
      ? 'Lolos dengan Revisi Anggaran'
      : totalScore >= 65
      ? 'Lolos dengan Revisi Substansi'
      : 'Tidak Direkomendasikan'
  );

  const handleScoreChange = (id: string, newScore: number) => {
    setCriteria(
      criteria.map((c) => (c.id === id ? { ...c, score: newScore } : c))
    );
  };

  const handleNotesChange = (id: string, notes: string) => {
    setCriteria(
      criteria.map((c) => (c.id === id ? { ...c, notes } : c))
    );
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const review: ReviewAssessment = {
      id: `rev-${Date.now()}`,
      reviewerId: `rev-curr`,
      reviewerName,
      reviewerNidn,
      reviewDate: new Date().toISOString().split('T')[0],
      criteria,
      totalScore,
      recommendation,
      notes: generalNotes,
    };

    onSubmitReview(proposal.id, review);
  };

  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-3xl max-h-[92vh] flex flex-col overflow-hidden animate-in fade-in zoom-in-95 duration-200">
        {/* Modal Header */}
        <div className="px-6 py-4 bg-slate-900 text-white flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-lg bg-amber-500 text-slate-950 flex items-center justify-center font-bold">
              <Award className="w-5 h-5" />
            </div>
            <div>
              <h2 className="text-base font-bold text-white">Lembar Penilaian Reviewer LPPM</h2>
              <p className="text-xs text-slate-300">Desk Evaluation Proposal Hibah Perguruan Tinggi</p>
            </div>
          </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>

        {/* Proposal Quick Identity */}
        <div className="bg-slate-50 border-b border-slate-200 px-6 py-3 text-xs">
          <div className="font-mono text-[10px] text-slate-500 mb-0.5">{proposal.code}</div>
          <div className="font-bold text-slate-900 line-clamp-1">{proposal.title}</div>
          <div className="text-slate-600 mt-1 flex flex-wrap gap-2 text-[11px]">
            <span>Ketua: <b>{proposal.leader.name}</b></span>
            <span>•</span>
            <span>Skema: <b>{proposal.scheme}</b></span>
            <span>•</span>
            <span>Usulan RAB: <b>{formatRupiah(proposal.requestedBudget)}</b></span>
          </div>
        </div>

        {/* Review Form Body */}
        <div className="p-6 overflow-y-auto flex-1 text-xs space-y-6">
          {/* Reviewer identity input */}
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 bg-slate-50 p-3.5 rounded-xl border border-slate-200">
            <div>
              <label className="block text-[11px] font-semibold text-slate-700 mb-1">Nama Reviewer:</label>
              <input
                type="text"
                value={reviewerName}
                onChange={(e) => setReviewerName(e.target.value)}
                className="w-full p-2 bg-white border border-slate-300 rounded-lg text-slate-900"
              />
            </div>
            <div>
              <label className="block text-[11px] font-semibold text-slate-700 mb-1">NIDN Reviewer:</label>
              <input
                type="text"
                value={reviewerNidn}
                onChange={(e) => setReviewerNidn(e.target.value)}
                className="w-full p-2 bg-white border border-slate-300 rounded-lg font-mono text-slate-900"
              />
            </div>
          </div>

          {/* Criteria scoring rubrics */}
          <div className="space-y-4">
            <h4 className="font-bold text-slate-900 text-sm flex items-center justify-between">
              <span>Rubrik Kriteria Penilaian Berbobot:</span>
              <span className="text-xs text-blue-700 font-bold">Skala Nilai 1 (Sangat Buruk) - 5 (Istimewa)</span>
            </h4>

            {criteria.map((c) => (
              <div key={c.id} className="bg-white border border-slate-200 rounded-xl p-4 space-y-2.5 shadow-xs">
                <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
                  <div>
                    <span className="font-bold text-slate-900 text-xs">
                      {c.label} <span className="text-blue-600">(Bobot {c.weight}%)</span>
                    </span>
                    <p className="text-slate-500 text-[11px] mt-0.5">{c.description}</p>
                  </div>

                  {/* Score Selector (1-5 with radio buttons) */}
                  <div className="flex items-center gap-1.5 shrink-0">
                    {[1, 2, 3, 4, 5].map((scoreVal) => (
                      <button
                        key={scoreVal}
                        type="button"
                        onClick={() => handleScoreChange(c.id, scoreVal)}
                        className={`w-8 h-8 rounded-lg font-bold text-xs flex items-center justify-center transition-all cursor-pointer ${
                          c.score === scoreVal
                            ? 'bg-blue-600 text-white shadow-xs ring-2 ring-blue-400/30'
                            : 'bg-slate-100 text-slate-700 hover:bg-slate-200'
                        }`}
                      >
                        {scoreVal}
                      </button>
                    ))}
                  </div>
                </div>

                <input
                  type="text"
                  placeholder="Catatan khusus reviewer untuk kriteria ini..."
                  value={c.notes || ''}
                  onChange={(e) => handleNotesChange(c.id, e.target.value)}
                  className="w-full p-2 bg-slate-50 border border-slate-200 rounded-lg text-[11px] text-slate-800"
                />
              </div>
            ))}
          </div>

          {/* Total Score & Recommendation Summary */}
          <div className="bg-slate-900 text-white rounded-xl p-5 space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <span className="text-xs text-slate-400 uppercase tracking-wider block font-bold">
                  Total Nilai Terbobot (Maks 100)
                </span>
                <div className="text-3xl font-black text-amber-400 mt-1">{totalScore}</div>
              </div>

              <div className="text-right">
                <span className="text-xs text-slate-400 block mb-1">Rekomendasi Reviewer:</span>
                <select
                  value={recommendation}
                  onChange={(e) => setRecommendation(e.target.value as any)}
                  className="bg-slate-800 border border-slate-700 text-white font-bold text-xs p-2 rounded-lg"
                >
                  <option value="Lolos Tanpa Revisi">Lolos Tanpa Revisi</option>
                  <option value="Lolos dengan Revisi Anggaran">Lolos dengan Revisi Anggaran</option>
                  <option value="Lolos dengan Revisi Substansi">Lolos dengan Revisi Substansi</option>
                  <option value="Tidak Direkomendasikan">Tidak Direkomendasikan</option>
                </select>
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-300 mb-1">
                Catatan Kesimpulan / Feedback Perbaikan untuk Pengusul:
              </label>
              <textarea
                rows={3}
                value={generalNotes}
                onChange={(e) => setGeneralNotes(e.target.value)}
                className="w-full p-2.5 bg-slate-800 border border-slate-700 text-white rounded-lg text-xs"
              />
            </div>
          </div>
        </div>

        {/* Modal Footer */}
        <div className="px-6 py-3.5 bg-slate-50 border-t border-slate-200 flex items-center justify-between text-xs">
          <button
            type="button"
            onClick={onClose}
            className="px-4 py-2 border border-slate-300 rounded-lg text-slate-700 hover:bg-slate-100 font-medium cursor-pointer"
          >
            Batal
          </button>

          <button
            type="button"
            onClick={handleSubmit}
            className="px-5 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-lg flex items-center gap-1.5 cursor-pointer shadow-xs"
          >
            <CheckCircle2 className="w-4 h-4" /> Simpan Penilaian Reviewer
          </button>
        </div>
      </div>
    </div>
  );
};
