'use client';

import { useAppStore } from '@/stores/app-store';
import { useEffect, useState, useRef } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { FileText, Printer, Download } from 'lucide-react';

interface SantriOption {
  id: string;
  nama: string;
  kelas: string;
}

interface HafalanItem {
  surah: string;
  ayatMulai: number;
  ayatAkhir: number;
  status: string;
  tanggal: string;
  catatan: string | null;
}

interface NgajiItem {
  juz: number;
  halamanMulai: number;
  halamanAkhir: number;
  tanggal: string;
  kualitas: string;
  catatan: string | null;
}

const JILID_OPTIONS = ['Jilid 1', 'Jilid 2', 'Jilid 3', 'Jilid 4', 'Jilid 5', 'Jilid 6', 'Ghorib', 'Tajwid Dasar'];
const TOTAL_JILID = JILID_OPTIONS.length;

interface JilidItem {
  namaJilid: string;
  halaman: number | null;
  status: string;
  tanggalSelesai: string | null;
  catatanGuru: string | null;
}

export default function LaporanPage() {
  const { token } = useAppStore();
  const [santriOptions, setSantriOptions] = useState<SantriOption[]>([]);
  const [selectedSantri, setSelectedSantri] = useState('');
  const [hafalan, setHafalan] = useState<HafalanItem[]>([]);
  const [ngaji, setNgaji] = useState<NgajiItem[]>([]);
  const [jilid, setJilid] = useState<JilidItem[]>([]);
  const [loading, setLoading] = useState(false);
  const printRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!token) return;
    fetch('/api/santri', { headers: { Authorization: `Bearer ${token}` } })
      .then((r) => r.json())
      .then((d) => { setSantriOptions(d); if (d.length > 0) setSelectedSantri(d[0].id); });
  }, [token]);

  useEffect(() => {
    if (!token || !selectedSantri) return;
    const headers = { Authorization: `Bearer ${token}` };

    Promise.all([
      fetch(`/api/hafalan?santriId=${selectedSantri}`, { headers }).then((r) => r.json()),
      fetch(`/api/ngaji?santriId=${selectedSantri}`, { headers }).then((r) => r.json()),
      fetch(`/api/jilid?santriId=${selectedSantri}`, { headers }).then((r) => r.json()),
    ]).then(([h, n, j]) => {
      setHafalan(h);
      setNgaji(n);
      setJilid(j);
    });
  }, [token, selectedSantri]);

  const santri = santriOptions.find((s) => s.id === selectedSantri);
  const jilidSelesai = jilid.filter((j) => j.status === 'SELESAI').length;
  const hafalanKuat = hafalan.filter((h) => h.status === 'KUAT').length;

  const handlePrint = () => {
    const printWindow = window.open('', '_blank');
    if (!printWindow || !printRef.current) return;

    printWindow.document.write(`
      <!DOCTYPE html>
      <html>
      <head>
        <title>Laporan Hafalan - ${santri?.nama}</title>
        <style>
          * { margin: 0; padding: 0; box-sizing: border-box; }
          body { font-family: 'Segoe UI', Arial, sans-serif; padding: 20px; color: #1a1a1a; font-size: 12px; }
          .header { text-align: center; border-bottom: 3px double #059669; padding-bottom: 16px; margin-bottom: 24px; }
          .header h1 { font-size: 18px; color: #059669; }
          .header p { color: #666; font-size: 11px; margin-top: 4px; }
          .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 20px; }
          .info-item { font-size: 12px; } .info-item span { font-weight: 600; }
          .section { margin-bottom: 20px; page-break-inside: avoid; }
          .section h2 { font-size: 14px; color: #059669; border-bottom: 1px solid #e5e7eb; padding-bottom: 6px; margin-bottom: 10px; }
          table { width: 100%; border-collapse: collapse; font-size: 11px; }
          th { background: #f0fdf4; color: #065f46; padding: 6px 8px; text-align: left; font-weight: 600; border: 1px solid #e5e7eb; }
          td { padding: 5px 8px; border: 1px solid #e5e7eb; }
          tr:nth-child(even) { background: #fafafa; }
          .badge { padding: 2px 8px; border-radius: 9999px; font-size: 10px; font-weight: 600; }
          .badge-kuat { background: #d1fae5; color: #065f46; }
          .badge-murojaah { background: #fef3c7; color: #92400e; }
          .badge-baru { background: #dbeafe; color: #1e40af; }
          .juz-grid { display: grid; grid-template-columns: repeat(10, 1fr); gap: 4px; margin-top: 8px; }
          .juz-cell { aspect-ratio: 1; border-radius: 6px; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: 600; color: white; }
          .juz-selesai { background: #059669; }
          .juz-proses { background: #d97706; }
          .juz-belum { background: #d1d5db; }
          .footer { margin-top: 32px; text-align: center; color: #9ca3af; font-size: 10px; border-top: 1px solid #e5e7eb; padding-top: 12px; }
          .stats-row { display: flex; gap: 16px; margin-bottom: 20px; }
          .stat-box { flex: 1; background: #f0fdf4; border-radius: 8px; padding: 10px; text-align: center; }
          .stat-box .num { font-size: 24px; font-weight: 700; color: #059669; }
          .stat-box .label { font-size: 10px; color: #666; }
          @media print { body { padding: 10px; } }
        </style>
      </head>
      <body>
        ${printRef.current.innerHTML}
        <script>window.onload = function() { window.print(); window.close(); }</script>
      </body>
      </html>
    `);
    printWindow.document.close();
  };

  const badgeClass = (s: string) => s === 'KUAT' ? 'badge-kuat' : s === "MUROJA'AH" ? 'badge-murojaah' : 'badge-baru';

  return (
    <div className="space-y-4">
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
        <div>
          <h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
            <FileText className="w-5 h-5 text-emerald-600" /> Laporan & Cetak
          </h1>
          <p className="text-sm text-gray-500">Cetak rapor hafalan dan progres bacaan santri</p>
        </div>
      </div>

      {/* Santri Selector */}
      <Card className="border-0 shadow-sm">
        <CardContent className="p-4 flex flex-col sm:flex-row items-start sm:items-center gap-3">
          <label className="text-sm font-medium text-gray-700">Pilih Santri:</label>
          <Select value={selectedSantri} onValueChange={setSelectedSantri}>
            <SelectTrigger className="w-full sm:w-72"><SelectValue placeholder="Pilih santri" /></SelectTrigger>
            <SelectContent>
              {santriOptions.map((s) => <SelectItem key={s.id} value={s.id}>{s.nama} ({s.kelas})</SelectItem>)}
            </SelectContent>
          </Select>
          <Button className="bg-emerald-600 hover:bg-emerald-700 gap-1.5" onClick={handlePrint} disabled={!selectedSantri || loading}>
            <Printer className="w-4 h-4" /> Cetak Laporan
          </Button>
        </CardContent>
      </Card>

      {/* Print Preview */}
      {selectedSantri && !loading && (
        <Card className="border-0 shadow-sm">
          <CardContent className="p-4 md:p-6">
            <div ref={printRef}>
              {/* Header */}
              <div className="header">
                <h1>Laporan Progres Hafalan & Bacaan Al-Quran</h1>
                <p>Metode Ummi — Tahun Ajaran 2025/2026</p>
              </div>

              {/* Info */}
              <div className="info-grid">
                <div className="info-item"><span>Nama:</span> {santri?.nama}</div>
                <div className="info-item"><span>Kelas:</span> {santri?.kelas}</div>
                <div className="info-item"><span>Tanggal Cetak:</span> {new Date().toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' })}</div>
              </div>

              {/* Stats */}
              <div className="stats-row">
                <div className="stat-box"><div className="num">{hafalan.length}</div><div className="label">Total Hafalan</div></div>
                <div className="stat-box"><div className="num">{hafalanKuat}</div><div className="label">Hafalan Kuat</div></div>
                <div className="stat-box"><div className="num">{jilidSelesai}</div><div className="label">Jilid Selesai</div></div>
                <div className="stat-box"><div className="num">{ngaji.length}</div><div className="label">Sesi Ngaji</div></div>
              </div>

              {/* Hafalan Table */}
              <div className="section">
                <h2>Daftar Hafalan</h2>
                <table>
                  <thead>
                    <tr><th>No</th><th>Surah</th><th>Ayat</th><th>Status</th><th>Tanggal</th><th>Catatan</th></tr>
                  </thead>
                  <tbody>
                    {hafalan.map((h, i) => (
                      <tr key={i}>
                        <td>{i + 1}</td>
                        <td>{h.surah}</td>
                        <td>{h.ayatMulai} – {h.ayatAkhir}</td>
                        <td><span className={`badge ${badgeClass(h.status)}`}>{h.status}</span></td>
                        <td>{new Date(h.tanggal).toLocaleDateString('id-ID')}</td>
                        <td>{h.catatan || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Ngaji Table */}
              <div className="section">
                <h2>Riwayat Ngaji</h2>
                <table>
                  <thead>
                    <tr><th>No</th><th>Juz</th><th>Halaman</th><th>Kualitas</th><th>Tanggal</th><th>Catatan</th></tr>
                  </thead>
                  <tbody>
                    {ngaji.map((n, i) => (
                      <tr key={i}>
                        <td>{i + 1}</td>
                        <td>{n.juz}</td>
                        <td>{n.halamanMulai} – {n.halamanAkhir}</td>
                        <td>{n.kualitas === 'BAIK_SEKALI' ? 'Baik Sekali' : n.kualitas === 'BAIK' ? 'Baik' : n.kualitas}</td>
                        <td>{new Date(n.tanggal).toLocaleDateString('id-ID')}</td>
                        <td>{n.catatan || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {/* Jilid Map */}
              <div className="section">
                <h2>Peta Progres Jilid ({TOTAL_JILID} Jilid)</h2>
                <div className="juz-grid" style="grid-template-columns: repeat(8, 1fr);">
                  {JILID_OPTIONS.map((jilidName) => {
                    const j = jilid.find((x) => x.namaJilid === jilidName);
                    const status = j?.status || 'BELUM';
                    const cls = status === 'SELESAI' ? 'juz-selesai' : status === 'PROSES' ? 'juz-proses' : 'juz-belum';
                    const label = jilidName.startsWith('Jilid ') ? jilidName.replace('Jilid ', 'J') : jilidName;
                    return <div key={jilidName} className={`juz-cell ${cls}`} style="font-size:9px;">{label}</div>;
                  })}
                </div>
                <div style={{ display: 'flex', gap: '16px', marginTop: '8px', fontSize: '10px', color: '#666' }}>
                  <span><span style={{ display: 'inline-block', width: '10px', height: '10px', borderRadius: '3px', background: '#059669', marginRight: '4px' }}></span>Selesai</span>
                  <span><span style={{ display: 'inline-block', width: '10px', height: '10px', borderRadius: '3px', background: '#d97706', marginRight: '4px' }}></span>Proses</span>
                  <span><span style={{ display: 'inline-block', width: '10px', height: '10px', borderRadius: '3px', background: '#d1d5db', marginRight: '4px' }}></span>Belum</span>
                </div>
              </div>

              {/* Jilid Detail */}
              <div className="section">
                <h2>Detail Progres Jilid</h2>
                <table>
                  <thead>
                    <tr><th>Jilid</th><th>Halaman</th><th>Status</th><th>Tanggal Selesai</th><th>Catatan Guru</th></tr>
                  </thead>
                  <tbody>
                    {jilid.filter((j) => j.status !== 'BELUM').map((j, i) => (
                      <tr key={i}>
                        <td>{j.namaJilid}</td>
                        <td>{j.halaman || '-'}</td>
                        <td><span className={`badge ${j.status === 'SELESAI' ? 'badge-kuat' : 'badge-murojaah'}`}>{j.status}</span></td>
                        <td>{j.tanggalSelesai ? new Date(j.tanggalSelesai).toLocaleDateString('id-ID') : '-'}</td>
                        <td>{j.catatanGuru || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              <div className="footer">
                <p>Monitoring Ummi — Dicetak pada {new Date().toLocaleString('id-ID')}</p>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}