import { useState, useEffect } from 'react';
import api from '../utils/api';
import { Icons } from '../components/icons/Icons';
import { useAuth } from '../context/AuthContext';
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 TYPE_COLORS = {
  lost: 'bg-rd/15 text-rd',
  accidentally_damaged: 'bg-or/15 text-or',
  burned: 'bg-rd/15 text-rd',
  broken: 'bg-yl/15 text-yl',
  expired: 'bg-t3/15 text-t3',
  contaminated: 'bg-pr/15 text-pr',
  spillage: 'bg-ac/15 text-ac',
  recalled: 'bg-yl/15 text-yl',
  other: 'bg-t3/15 text-t3',
};

const STATUS_COLORS = {
  pending: 'bg-yl/15 text-yl',
  processed: 'bg-ac/15 text-ac',
  resolved: 'bg-gr/15 text-gr',
};

export default function StockReports({ refetch, nav }) {
  const { hasRole } = useAuth();
  const [reports, setReports] = useState([]);
  const [filter, setFilter] = useState('all');
  const [search, setSearch] = useState('');
  const [detail, setDetail] = useState(null);
  const [resolveCfm, setResolveCfm] = useState(null);
  const [deleteCfm, setDeleteCfm] = useState(null);
  const [processNotes, setProcessNotes] = useState('');

  const fetchReports = async () => {
    try {
      const res = await api.get('/stock-reports');
      setReports(res.data);
    } catch {}
  };

  useEffect(() => { fetchReports(); }, []);

  const filtered = reports
    .filter(r => filter === 'all' || r.status === filter)
    .filter(r => {
      if (!search.trim()) return true;
      const q = search.toLowerCase();
      return (r.product_name || '').toLowerCase().includes(q) ||
        (r.reporter_name || '').toLowerCase().includes(q) ||
        (r.reduction_type || '').toLowerCase().includes(q) ||
        (r.description || '').toLowerCase().includes(q);
    });

  const counts = {
    total: reports.length,
    pending: reports.filter(r => r.status === 'pending').length,
    resolved: reports.filter(r => r.status === 'resolved').length,
  };

  const handleResolve = async () => {
    if (!resolveCfm) return;
    try {
      await api.put(`/stock-reports/${resolveCfm.id}/resolve`, { notes: processNotes });
      setResolveCfm(null);
      setProcessNotes('');
      fetchReports();
      refetch();
    } catch {}
  };

  const handleDelete = async () => {
    if (!deleteCfm) return;
    try {
      await api.delete(`/stock-reports/${deleteCfm.id}`);
      setDeleteCfm(null);
      if (detail?.id === deleteCfm.id) setDetail(null);
      fetchReports();
      refetch();
    } catch {}
  };

  return (
    <div>
      <div className="flex justify-between items-start mb-5">
        <div>
          <h1 className="text-xl font-bold mb-0.5">Stock Reports</h1>
          <p className="text-t2 text-xs">
            {hasRole('supplier', 'master_admin') ? 'Review stock reduction reports from cashiers' : 'Your submitted stock reduction reports'}
          </p>
        </div>
        <div className="flex gap-1.5 flex-wrap">
          {reports.length > 0 && (
            <>
              <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(reports, 'PeptideOS-Reports-Current.xlsx', 'Current View')}
              >
                <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(reports, 'PeptideOS-Reports-Current.pdf', 'Current View')}
              >
                <Icons.FilePdf /> PDF
              </button>
            </>
          )}
          {hasRole('master_admin') && (
            <button
              className="bg-ac text-white px-3 py-1.5 rounded-md text-xs font-semibold flex items-center gap-1 hover:bg-ac/90"
              onClick={() => nav('archive-reports')}
            >
              <Icons.Archive /> Archive Database
            </button>
          )}
        </div>
      </div>

      {/* Summary Cards */}
      <div className="flex gap-2.5 flex-wrap mb-4">
        {[
          { l: 'Total', v: counts.total, c: 'border-l-ac' },
          { l: 'Pending', v: counts.pending, c: counts.pending > 0 ? 'border-l-yl' : 'border-l-t3' },
          { l: 'Resolved', v: counts.resolved, c: 'border-l-gr' },
        ].map((s, i) => (
          <div key={i} className={`bg-s1 border border-bd rounded-[10px] py-3 px-4 flex-1 min-w-[120px] border-l-[3px] ${s.c}`}>
            <div className="text-[10px] text-t2 mb-0.5">{s.l}</div>
            <div className="text-lg font-bold">{s.v}</div>
          </div>
        ))}
      </div>

      {/* Filters */}
      <div className="flex gap-2 mb-3.5 flex-wrap items-center">
        <div className="flex items-center gap-2 bg-s2 border border-bd rounded-md px-2.5 py-1 flex-1 max-w-[240px]">
          <Icons.Search />
          <input className="bg-transparent border-none text-t1 text-[13px] w-full outline-none" placeholder="Search..." value={search} onChange={(e) => setSearch(e.target.value)} />
        </div>
        {['all', 'pending', 'resolved'].map((f) => (
          <button key={f} className={`px-2.5 py-1 rounded-md text-[11px] font-semibold border ${filter === f ? 'bg-ac text-white border-ac' : 'border-bd text-t2 hover:bg-s2'}`}
            onClick={() => setFilter(f)}>{f === 'all' ? 'All' : f[0].toUpperCase() + f.slice(1)}</button>
        ))}
      </div>

      {/* Reports List */}
      <div className="bg-s1 border border-bd rounded-[10px] p-4">
        {filtered.length === 0 ? (
          <p className="text-t2 text-xs text-center py-6">No reports found</p>
        ) : filtered.map((r) => (
          <div key={r.id} className="flex justify-between items-center py-2.5 border-b border-bd last:border-0">
            <div className="flex-1 cursor-pointer" onClick={() => setDetail(r)}>
              <div className="flex items-center gap-2 mb-1">
                <span className="font-semibold text-[13px]">{r.product_name || '?'}</span>
                <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${TYPE_COLORS[r.reduction_type] || ''}`}>
                  {TYPE_LABELS[r.reduction_type] || r.reduction_type}
                </span>
                <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${STATUS_COLORS[r.status] || ''}`}>
                  {r.status}
                </span>
              </div>
              <div className="text-[11px] text-t2">
                {r.description?.slice(0, 80)}{r.description?.length > 80 ? '...' : ''}
              </div>
              <div className="text-[10px] text-t3 mt-0.5">
                Qty: <span className="text-rd font-semibold">{r.qty}</span> &middot;
                By: {r.reporter_name || r.reporter_username || '?'} &middot;
                {r.created_at ? new Date(r.created_at).toLocaleString() : ''}
              </div>
            </div>
            <div className="flex gap-2 items-center ml-3" onClick={(e) => e.stopPropagation()}>
              <button className="p-1.5 rounded text-t2 hover:text-ac hover:bg-ac/10" title="View" onClick={() => setDetail(r)}><Icons.Eye /></button>
              {hasRole('master_admin', 'supplier') && r.status !== 'resolved' && (
                <button className="bg-gr text-white px-3 py-1.5 rounded-md text-xs font-semibold hover:bg-gr/90" onClick={() => { setProcessNotes(''); setResolveCfm(r); }}>
                  Resolve
                </button>
              )}
              {hasRole('master_admin', 'supplier') && (
                <button className="p-1.5 rounded text-rd hover:bg-rd/10" title="Delete" onClick={() => setDeleteCfm(r)}><Icons.Trash /></button>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* Detail Modal */}
      <Modal open={!!detail} onClose={() => setDetail(null)} title="Stock Reduction Report" w={560}>
        {detail && (
          <>
            <div className="flex gap-2 mb-3">
              <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${TYPE_COLORS[detail.reduction_type] || ''}`}>
                {TYPE_LABELS[detail.reduction_type] || detail.reduction_type}
              </span>
              <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold ${STATUS_COLORS[detail.status] || ''}`}>
                {detail.status}
              </span>
            </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">Product</div>
              <div className="text-sm font-bold">{detail.product_name}</div>
              <div className="text-xs text-t2">{detail.mg}mg/{detail.ml}ml &middot; Batch: {detail.batch} &middot; Route: {detail.route}</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">Report Details</div>
              <div className="text-xs mb-1"><span className="text-t2">Quantity:</span> <span className="text-rd font-bold">{detail.qty}</span></div>
              <div className="text-xs mb-1"><span className="text-t2">Type:</span> {TYPE_LABELS[detail.reduction_type]}</div>
              <div className="text-xs"><span className="text-t2">Description:</span></div>
              <div className="text-[13px] mt-1 leading-relaxed">{detail.description}</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">Evidence Photos</div>
              <div className="flex gap-2">
                {detail.photo_1 && <img src={detail.photo_1} alt="Photo 1" className="w-1/2 rounded-md border border-bd object-cover max-h-[200px]" />}
                {detail.photo_2 && <img src={detail.photo_2} alt="Photo 2" className="w-1/2 rounded-md border border-bd object-cover max-h-[200px]" />}
              </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">Reporter</div>
              <div className="text-xs">{detail.reporter_name || detail.reporter_username}</div>
              <div className="text-[10px] text-t3">{detail.created_at ? new Date(detail.created_at).toLocaleString() : ''}</div>
            </div>

            {detail.processor_name && (
              <div className="bg-s2 rounded-md p-3 mb-3 border border-bd">
                <div className="text-[11px] font-bold text-ac uppercase mb-2">Processed By</div>
                <div className="text-xs">{detail.processor_name}</div>
                <div className="text-[10px] text-t3">{detail.processed_at ? new Date(detail.processed_at).toLocaleString() : ''}</div>
                {detail.notes && <div className="text-xs text-t2 mt-1">Notes: {detail.notes}</div>}
              </div>
            )}

            <div className="flex justify-end gap-2 mt-2 flex-wrap">
              <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>
              {hasRole('master_admin', 'supplier') && detail.status !== 'resolved' && (
                <button className="bg-gr text-white px-4 py-1.5 rounded-md text-sm font-semibold hover:bg-gr/90" onClick={() => { setProcessNotes(''); setResolveCfm(detail); setDetail(null); }}>
                  Resolve Report
                </button>
              )}
            </div>
          </>
        )}
      </Modal>

      {/* Resolve Confirm */}
      <Modal open={!!resolveCfm} onClose={() => setResolveCfm(null)} title="Resolve Stock Report" w={420}>
        {resolveCfm && (
          <>
            <p className="text-[13px] text-t2 mb-2">Resolve report for <strong className="text-t1">{resolveCfm.product_name}</strong>?</p>
            <div className="bg-rd/10 border border-rd/30 rounded-md p-2.5 mb-3 text-[12px] text-t1 flex items-start gap-2">
              <span className="text-rd flex-shrink-0 mt-0.5"><Icons.Alert /></span>
              <span>Stock akan otomatis berkurang sebanyak <strong className="text-rd">{resolveCfm.qty}</strong> unit dan tercatat di history produk.</span>
            </div>
            <Field label="Notes (optional)">
              <textarea className="w-full p-1.5 px-2.5 bg-s2 border border-bd rounded-md text-t1 text-[13px] min-h-[60px] resize-y" value={processNotes} onChange={(e) => setProcessNotes(e.target.value)} placeholder="Add notes..." />
            </Field>
            <div className="flex justify-end gap-2 mt-2">
              <button className="px-3.5 py-1.5 rounded-md border border-bd text-t2 text-xs font-semibold" onClick={() => setResolveCfm(null)}>Cancel</button>
              <button className="bg-gr text-white px-3.5 py-1.5 rounded-md text-xs font-semibold" onClick={handleResolve}>Confirm Resolve</button>
            </div>
          </>
        )}
      </Modal>

      {/* Delete Confirm */}
      <Confirm open={!!deleteCfm} onClose={() => setDeleteCfm(null)} icon="🗑️" title="Delete Report?"
        desc={`Delete this report for "${deleteCfm?.product_name}"?`}
        cStyle="d" cLabel="Yes, Delete"
        details={[{ i: '⚠️', t: 'This action cannot be undone' }]}
        onConfirm={handleDelete}
      />
    </div>
  );
}
