import { useState, useEffect } from 'react';
import api from '../utils/api';
import { Icons } from '../components/icons/Icons';
import Modal from '../components/ui/Modal';
import Confirm from '../components/ui/Confirm';
import Field from '../components/ui/Field';
import { exportReportsPDF, exportReportsExcel } from '../utils/reportExport';

const TYPE_LABELS = {
  lost: 'Lost',
  accidentally_damaged: 'Accidentally Damaged',
  burned: 'Burned',
  broken: 'Broken',
  expired: 'Expired',
  contaminated: 'Contaminated',
  spillage: 'Spillage',
  recalled: 'Recalled',
  other: 'Other',
};

const UNLOCK_KEY = 'reportArchiveUnlocked';

const MONTH_NAME = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
const formatMonthLabel = (ym) => {
  const [y, m] = ym.split('-');
  return `${MONTH_NAME[parseInt(m) - 1]} ${y}`;
};

export default function ArchiveReports({ nav }) {
  const [unlocked, setUnlocked] = useState(() => sessionStorage.getItem(UNLOCK_KEY) === '1');
  const [password, setPassword] = useState('');
  const [unlockError, setUnlockError] = useState('');
  const [unlocking, setUnlocking] = useState(false);

  const [months, setMonths] = useState([]);
  const [selectedMonth, setSelectedMonth] = useState(null);
  const [monthReports, setMonthReports] = useState([]);
  const [loading, setLoading] = useState(false);
  const [detail, setDetail] = useState(null);
  const [deleteMonthCfm, setDeleteMonthCfm] = useState(null);

  const tryUnlock = async () => {
    setUnlocking(true);
    setUnlockError('');
    try {
      await api.post('/stock-reports/archive/unlock', { password });
      sessionStorage.setItem(UNLOCK_KEY, '1');
      setUnlocked(true);
      setPassword('');
    } catch (err) {
      setUnlockError(err.response?.data?.error || 'Failed to unlock');
    } finally {
      setUnlocking(false);
    }
  };

  const fetchMonths = async () => {
    try {
      const res = await api.get('/stock-reports/archive/months');
      setMonths(res.data);
    } catch {}
  };

  const openMonth = async (ym) => {
    setSelectedMonth(ym);
    setLoading(true);
    try {
      const res = await api.get(`/stock-reports/archive/month/${ym}`);
      setMonthReports(res.data);
    } catch {
      setMonthReports([]);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteMonth = async () => {
    if (!deleteMonthCfm) return;
    try {
      await api.delete(`/stock-reports/archive/month/${deleteMonthCfm}`);
      setDeleteMonthCfm(null);
      if (selectedMonth === deleteMonthCfm) {
        setSelectedMonth(null);
        setMonthReports([]);
      }
      fetchMonths();
    } catch (err) {
      alert(err.response?.data?.error || 'Failed to delete');
    }
  };

  useEffect(() => {
    if (unlocked) fetchMonths();
  }, [unlocked]);

  // Password gate
  if (!unlocked) {
    return (
      <div className="flex items-center justify-center min-h-[60vh] px-4">
        <div className="bg-s1 border border-bd rounded-xl p-6 w-full max-w-[400px]">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-lg bg-pr/15 text-pr flex items-center justify-center">
              <Icons.Lock />
            </div>
            <div>
              <h2 className="text-lg font-bold">Firewall Report Produk</h2>
              <p className="text-xs text-t2">Masukkan password untuk akses database laporan</p>
            </div>
          </div>
          <Field label="Password">
            <input
              type="password"
              className="w-full p-2 px-3 bg-s2 border border-bd rounded-md text-t1 text-[13px] outline-none focus:border-ac"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && tryUnlock()}
              placeholder="Enter firewall password..."
              autoFocus
            />
          </Field>
          {unlockError && <div className="text-rd text-xs mb-2">{unlockError}</div>}
          <div className="flex gap-2 mt-3">
            <button
              className="flex-1 px-3.5 py-2 rounded-md border border-bd text-t2 text-xs font-semibold hover:bg-s2"
              onClick={() => nav('stock-reports')}
            >
              Cancel
            </button>
            <button
              className="flex-1 bg-ac text-white px-3.5 py-2 rounded-md text-xs font-semibold hover:bg-ac/90 disabled:opacity-50"
              onClick={tryUnlock}
              disabled={unlocking || !password}
            >
              {unlocking ? 'Verifying...' : 'Unlock'}
            </button>
          </div>
          <p className="text-[10px] text-t3 mt-3">
            Lupa password? Master admin dapat mengubahnya di Settings → Report Firewall Password.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-4 flex-wrap gap-2">
        <div>
          <div className="flex items-center gap-2 mb-0.5">
            <button className="text-t2 hover:text-t1 text-xs" onClick={() => nav('stock-reports')}>
              ← Back
            </button>
            <span className="text-t3 text-xs">/</span>
            <span className="text-xs text-t2">Stock Reports</span>
          </div>
          <h1 className="text-xl font-bold">Report Archive Database</h1>
          <p className="text-t2 text-xs">Folder laporan per bulan — cetak atau hapus permanen</p>
        </div>
        <button
          className="flex items-center gap-1.5 text-xs text-t2 hover:text-t1 border border-bd rounded-md px-2.5 py-1.5"
          onClick={() => {
            sessionStorage.removeItem(UNLOCK_KEY);
            setUnlocked(false);
          }}
        >
          <Icons.Lock /> Lock
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-4">
        {/* Month folders */}
        <div className="lg:col-span-4 bg-s1 border border-bd rounded-[10px] p-3">
          <div className="text-[11px] uppercase tracking-wide text-t3 font-semibold mb-2 px-1">Folders ({months.length})</div>
          {months.length === 0 ? (
            <p className="text-t2 text-xs text-center py-6">No reports yet</p>
          ) : months.map((m) => (
            <div
              key={m.month}
              className={`group flex items-center gap-2 p-2 rounded-md cursor-pointer mb-1 transition-colors ${
                selectedMonth === m.month ? 'bg-ac/20 border border-ac/40' : 'hover:bg-s2 border border-transparent'
              }`}
              onClick={() => openMonth(m.month)}
            >
              <span className={selectedMonth === m.month ? 'text-ac' : 'text-gold'}>
                {selectedMonth === m.month ? <Icons.FolderOpen /> : <Icons.Folder />}
              </span>
              <div className="flex-1 min-w-0">
                <div className="text-[13px] font-semibold truncate">{formatMonthLabel(m.month)}</div>
                <div className="text-[10px] text-t3">
                  {m.total} reports · {m.total_qty || 0} units
                  {m.archived > 0 && <span className="text-or ml-1">· {m.archived} archived</span>}
                </div>
              </div>
              <button
                className="opacity-0 group-hover:opacity-100 text-rd hover:bg-rd/10 p-1 rounded transition-opacity"
                title="Delete folder permanently"
                onClick={(e) => {
                  e.stopPropagation();
                  setDeleteMonthCfm(m.month);
                }}
              >
                <Icons.Trash />
              </button>
            </div>
          ))}
        </div>

        {/* Month content */}
        <div className="lg:col-span-8 bg-s1 border border-bd rounded-[10px] p-4">
          {!selectedMonth ? (
            <div className="flex items-center justify-center h-[400px] text-t3 text-sm">
              Pilih folder bulan untuk melihat isinya
            </div>
          ) : loading ? (
            <div className="flex items-center justify-center h-[400px] text-t3 text-sm">Loading...</div>
          ) : (
            <>
              <div className="flex justify-between items-center mb-3 pb-2 border-b border-bd">
                <div>
                  <h3 className="text-base font-bold">{formatMonthLabel(selectedMonth)}</h3>
                  <p className="text-[11px] text-t3">{monthReports.length} reports</p>
                </div>
                <div className="flex gap-2">
                  <button
                    className="bg-gr text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-gr/90 disabled:opacity-50"
                    disabled={monthReports.length === 0}
                    onClick={() => exportReportsExcel(monthReports, `PeptideOS-Reports-${selectedMonth}.xlsx`, formatMonthLabel(selectedMonth))}
                  >
                    <Icons.FileExcel /> Excel
                  </button>
                  <button
                    className="bg-rd text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-rd/90 disabled:opacity-50"
                    disabled={monthReports.length === 0}
                    onClick={() => exportReportsPDF(monthReports, `PeptideOS-Reports-${selectedMonth}.pdf`, formatMonthLabel(selectedMonth))}
                  >
                    <Icons.FilePdf /> PDF
                  </button>
                </div>
              </div>

              {monthReports.length === 0 ? (
                <p className="text-t2 text-xs text-center py-8">Folder kosong</p>
              ) : (
                <div className="max-h-[500px] overflow-y-auto">
                  {monthReports.map((r) => (
                    <div
                      key={r.id}
                      className="flex justify-between items-center py-2 border-b border-bd last:border-0 cursor-pointer hover:bg-s2 -mx-2 px-2 rounded"
                      onClick={() => setDetail(r)}
                    >
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2 mb-0.5">
                          <span className="font-semibold text-[13px] truncate">{r.product_name || '?'}</span>
                          <span className="px-1.5 py-0.5 rounded text-[9px] font-bold bg-rd/15 text-rd whitespace-nowrap">
                            {TYPE_LABELS[r.reduction_type] || r.reduction_type}
                          </span>
                          {r.archived_at && (
                            <span className="px-1.5 py-0.5 rounded text-[9px] font-bold bg-or/15 text-or">archived</span>
                          )}
                        </div>
                        <div className="text-[10px] text-t3">
                          Qty: <span className="text-rd font-semibold">{r.qty}</span> ·
                          By: {r.reporter_name || r.reporter_username || '?'} ·
                          {r.created_at ? new Date(r.created_at).toLocaleString() : ''}
                        </div>
                      </div>
                      <div className="flex gap-1 ml-2 text-t3">
                        {r.photo_1 && <Icons.Camera />}
                        {r.photo_2 && <Icons.Camera />}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </>
          )}
        </div>
      </div>

      {/* Report detail modal */}
      <Modal open={!!detail} onClose={() => setDetail(null)} title="Report Detail" w={560}>
        {detail && (
          <>
            <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
              <div className="text-[11px] font-bold text-ac uppercase mb-2">Product</div>
              <div className="text-sm font-bold">{detail.product_name}</div>
              <div className="text-xs text-t2">{detail.mg}mg/{detail.ml}ml · Batch: {detail.batch}</div>
            </div>
            <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
              <div className="text-[11px] font-bold text-ac uppercase mb-2">Details</div>
              <div className="text-xs mb-1"><span className="text-t2">Type:</span> {TYPE_LABELS[detail.reduction_type]}</div>
              <div className="text-xs mb-1"><span className="text-t2">Qty:</span> <span className="text-rd font-bold">{detail.qty}</span></div>
              <div className="text-xs mb-1"><span className="text-t2">Status:</span> {detail.status}{detail.archived_at ? ' (archived)' : ''}</div>
              <div className="text-xs mt-2 leading-relaxed">{detail.description}</div>
            </div>
            {(detail.photo_1 || detail.photo_2) && (
              <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
                <div className="text-[11px] font-bold text-ac uppercase mb-2">Evidence</div>
                <div className="flex gap-2">
                  {detail.photo_1 && <img src={detail.photo_1} alt="" className="w-1/2 rounded-md border border-bd object-cover max-h-[200px]" />}
                  {detail.photo_2 && <img src={detail.photo_2} alt="" className="w-1/2 rounded-md border border-bd object-cover max-h-[200px]" />}
                </div>
              </div>
            )}
            <div className="flex justify-end gap-2 mt-2">
              <button
                className="bg-gr text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-gr/90"
                onClick={() => exportReportsExcel([detail], `Report-${detail.id}.xlsx`, 'Single Report')}
              >
                <Icons.FileExcel /> Excel
              </button>
              <button
                className="bg-rd text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-rd/90"
                onClick={() => exportReportsPDF([detail], `Report-${detail.id}.pdf`, 'Single Report')}
              >
                <Icons.FilePdf /> PDF
              </button>
            </div>
          </>
        )}
      </Modal>

      {/* Delete month confirm */}
      <Confirm
        open={!!deleteMonthCfm}
        onClose={() => setDeleteMonthCfm(null)}
        title={`Hapus folder ${deleteMonthCfm ? formatMonthLabel(deleteMonthCfm) : ''}?`}
        desc="Semua laporan dan foto di bulan ini akan DIHAPUS PERMANEN dari database. Aksi ini tidak dapat dibatalkan."
        cStyle="d"
        cLabel="Yes, Delete Permanently"
        details={[
          { t: 'Data dan foto dihapus selamanya' },
          { t: 'Pastikan Anda sudah mengekspor PDF/Excel jika diperlukan' },
        ]}
        onConfirm={handleDeleteMonth}
      />
    </div>
  );
}
