'use client';

import React, { useState, useMemo, useEffect } from 'react';
import { FiDownload, FiFileText, FiSearch, FiClipboard, FiCheckCircle, FiClock } from 'react-icons/fi';
import styles from '../commonstyle/dattabale.module.css';
import { EnterpriseLoader } from '../../../../components/loader/loader';
import { Pagination } from '../companies/Pagination';
import AuditStatusRow from './AuditStatusRow';
import type { AuditNcStatusRow } from '@/lib/api/types/previous-nc.types';
import toast from 'react-hot-toast';
import { downloadAuditNcStatusReport } from '@/lib/api/previous-nc.api';
interface Props {
    rows: AuditNcStatusRow[];
    totals: { total: number; raised: number; pending: number };
    loading: boolean;
    canViewAll: boolean;
    auditorFilter: string; // 'all' or an auditor name (from the page's user filter)
    sourceFilter?: 'all' | 'QRS' | 'TQS' | 'NEW';   // 🆕 page source filter
    statusFilter?: 'all' | 'open' | 'closed'; // 🆕 page status filter
    year?: number;                            // 🆕 page year filter
    month?: number | 'all';                   // 🆕 page month filter
}

const thStyle: React.CSSProperties = {
    padding: '12px 10px', textAlign: 'left', fontSize: 10, fontWeight: 800,
    color: '#475569', textTransform: 'uppercase', letterSpacing: '0.06em',
    background: '#f8fafc', borderBottom: '1px solid #e2e8f0',
};

export default function AuditNcStatusTable({ rows, loading, canViewAll, auditorFilter, sourceFilter, statusFilter, year, month }: Props) {
    const [currentPage, setCurrentPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(10);
    const [localSearch, setLocalSearch] = useState('');
    const [downloading, setDownloading] = useState<null | 'excel' | 'pdf'>(null);
    // Apply auditor filter (from page) + local client-name search, on the frontend.

    // ── Server-side branded export (Excel / PDF) ──
    const handleServerExport = async (format: 'excel' | 'pdf') => {
        setDownloading(format);
        try {
            await downloadAuditNcStatusReport(format, {
                source: sourceFilter === 'QRS' || sourceFilter === 'TQS' ? sourceFilter : undefined,
                status: statusFilter === 'open' ? 'Pending' : statusFilter === 'closed' ? 'Raised' : undefined,
                auditor: auditorFilter && auditorFilter !== 'all' ? auditorFilter : undefined,
                year: year,
                month: month,
                search: localSearch || undefined,
            });
            toast.success(`${format === 'excel' ? 'Excel' : 'PDF'} report downloaded`);
        } catch (e: any) {
            toast.error(e?.message ?? 'Download failed');
        } finally {
            setDownloading(null);
        }
    };
    const filtered = useMemo(() => {
        let r = rows;
        if (auditorFilter && auditorFilter !== 'all') {
            const want = auditorFilter.trim().toLowerCase();
            r = r.filter((x) => x.auditor_names.some((n) => n.trim().toLowerCase() === want));
        }
        const q = localSearch.trim().toLowerCase();
        if (q) r = r.filter((x) => (x.company_name || '').toLowerCase().includes(q));
        return r;
    }, [rows, auditorFilter, localSearch]);

    // Totals recomputed from the filtered set, so the cards react to the filter.
    const t = useMemo(() => {
        const total = filtered.length;
        const raised = filtered.filter((x) => x.nc_status === 'NC Raised').length;
        return { total, raised, pending: total - raised };
    }, [filtered]);

    useEffect(() => { setCurrentPage(1); }, [filtered]);

    const totalPages = Math.max(1, Math.ceil(filtered.length / itemsPerPage));
    const startIndex = (currentPage - 1) * itemsPerPage;
    const pageRows = filtered.slice(startIndex, startIndex + itemsPerPage);

    // ── Excel export (CSV — opens directly in Excel) ──
    const exportCsv = () => {
        const header = ['Client', 'Source', 'Audit Type', 'Audit Date', 'Auditor', 'NC Status'];
        const lines = filtered.map((r) => [
            r.company_name ?? '',
            r.source,
            r.audit_kind === 'client' ? 'Initial Audit' : 'Surveillance',
            r.audit_date ? new Date(r.audit_date).toLocaleDateString('en-GB') : '',
            r.auditor_names.join('; '),
            r.nc_status,
        ]);
        const csv = [header, ...lines]
            .map((row) => row.map((c) => `"${String(c).replace(/"/g, '""')}"`).join(','))
            .join('\n');
        const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `audit-nc-status-${Date.now()}.csv`;
        a.click();
        URL.revokeObjectURL(url);
    };

    // ── PDF export (print window → Save as PDF) ──
    const exportPdf = () => {
        const w = window.open('', '_blank');
        if (!w) return;
        const body = filtered
            .map(
                (r) => `<tr>
          <td>${r.company_name ?? '—'}</td>
          <td>${r.source}</td>
          <td>${r.audit_kind === 'client' ? 'Initial Audit' : 'Surveillance'}</td>
          <td>${r.audit_date ? new Date(r.audit_date).toLocaleDateString('en-GB') : '—'}</td>
          <td>${r.auditor_names.join(', ') || '—'}</td>
          <td>${r.nc_status}</td>
        </tr>`,
            )
            .join('');
        w.document.write(`
      <html><head><title>Audit → NC Status</title>
      <style>
        body{font-family:Arial,sans-serif;padding:24px;color:#111}
        h2{color:#0f766e;margin:0 0 4px}
        .meta{color:#666;font-size:12px;margin-bottom:16px}
        table{width:100%;border-collapse:collapse;font-size:12px}
        th{background:#0f766e;color:#fff;text-align:left;padding:8px}
        td{padding:7px 8px;border-bottom:1px solid #eee}
        tr:nth-child(even) td{background:#f8fafc}
      </style></head><body>
        <h2>Audit → NC Status Report</h2>
        <div class="meta">Total ${t.total} &nbsp;|&nbsp; NC Raised ${t.raised} &nbsp;|&nbsp; NC Pending ${t.pending} &nbsp;|&nbsp; Generated ${new Date().toLocaleString()}</div>
        <table><thead><tr>
          <th>Client</th><th>Source</th><th>Audit Type</th><th>Audit Date</th><th>Auditor</th><th>NC Status</th>
        </tr></thead><tbody>${body}</tbody></table>
      </body></html>`);
        w.document.close();
        w.focus();
        setTimeout(() => w.print(), 300);
    };

    const cards = [
        { label: 'Total Audits', value: t.total, icon: <FiClipboard size={20} />, grad: 'linear-gradient(135deg,#0f766e,#14b8a6)' },
        { label: 'NC Raised', value: t.raised, icon: <FiCheckCircle size={20} />, grad: 'linear-gradient(135deg,#15803d,#22c55e)' },
        { label: 'NC Pending', value: t.pending, icon: <FiClock size={20} />, grad: 'linear-gradient(135deg,#b45309,#f59e0b)' },
    ];

    return (
        <div>
            {/* Scope banner */}
            <div style={{
                padding: '8px 14px', marginBottom: 14, borderRadius: 8, fontSize: 12, fontWeight: 700,
                background: canViewAll ? '#eef2ff' : '#fffbeb',
                color: canViewAll ? '#4338ca' : '#b45309',
                border: `1px solid ${canViewAll ? '#c7d2fe' : '#fde68a'}`,
                display: 'inline-flex', alignItems: 'center', gap: 6,
            }}>
                {canViewAll ? '🌐 Showing all auditors’ audits' : '👤 Showing only your assigned audits'}
            </div>

            {/* Modern KPI cards */}
            {/* Professional KPI cards — dashboard style */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit,minmax(200px,1fr))', gap: 16, marginBottom: 18 }}>
                {[
                    {
                        label: 'Total Audits', value: t.total, pct: 100, icon: <FiClipboard size={20} />,
                        bg: '#1e1b4b', line: '#818cf8', chip: 'rgba(129,140,248,0.18)', soft: '#c7d2fe', cap: '#a5b4fc',
                        caption: 'All scheduled audits in range'
                    },
                    {
                        label: 'NC Raised', value: t.raised, pct: t.total ? Math.round((t.raised / t.total) * 100) : 0, icon: <FiCheckCircle size={20} />,
                        bg: '#052e23', line: '#34d399', chip: 'rgba(52,211,153,0.18)', soft: '#6ee7b7', cap: '#6ee7b7',
                        caption: 'of audits have an NC'
                    },
                    {
                        label: 'NC Pending', value: t.pending, pct: t.total ? Math.round((t.pending / t.total) * 100) : 0, icon: <FiClock size={20} />,
                        bg: '#3a2206', line: '#fbbf24', chip: 'rgba(251,191,36,0.18)', soft: '#fcd34d', cap: '#fcd34d',
                        caption: 'still awaiting an NC'
                    },
                ].map((c) => (
                    <div key={c.label} style={{
                        position: 'relative', overflow: 'hidden', borderRadius: 18,
                        padding: '22px 22px 20px', background: c.bg, borderTop: `3px solid ${c.line}`,
                    }}>
                        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18 }}>
                            <span style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase', color: c.soft }}>
                                {c.label}
                            </span>
                            <span style={{
                                width: 38, height: 38, borderRadius: 11, background: c.chip, color: c.soft,
                                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                            }}>
                                {c.icon}
                            </span>
                        </div>
                        <div style={{ fontSize: 34, fontWeight: 800, lineHeight: 1, letterSpacing: '-0.02em', color: '#fff' }}>
                            {c.value.toLocaleString()}
                        </div>
                        <div style={{ marginTop: 14, height: 5, borderRadius: 99, background: 'rgba(255,255,255,0.12)', overflow: 'hidden' }}>
                            <div style={{ width: `${c.pct}%`, height: '100%', background: c.line }} />
                        </div>
                        <div style={{ marginTop: 10, fontSize: 12, color: c.cap }}>
                            {c.label === 'Total Audits' ? c.caption : `${c.pct}% ${c.caption}`}
                        </div>
                    </div>
                ))}
            </div>

            {/* Toolbar: search + export */}
            <div style={{ display: 'flex', gap: 10, marginBottom: 12, alignItems: 'center', flexWrap: 'wrap' }}>
                <div style={{ position: 'relative', flex: 1, minWidth: 220 }}>
                    <FiSearch size={15} style={{ position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)', color: '#94a3b8' }} />
                    <input
                        value={localSearch}
                        onChange={(e) => setLocalSearch(e.target.value)}
                        placeholder="Search by client name…"
                        style={{
                            width: '100%', padding: '10px 12px 10px 34px', borderRadius: 10,
                            border: '1px solid #e2e8f0', fontSize: 13, outline: 'none',
                        }}
                    />
                </div>
                <button onClick={() => handleServerExport('excel')} disabled={downloading !== null} style={btn('#15803d', '#f0fdf4', '#bbf7d0')}>
                    <FiDownload size={15} /> {downloading === 'excel' ? 'Exporting…' : 'Excel'}
                </button>
                <button onClick={() => handleServerExport('pdf')} disabled={downloading !== null} style={btn('#dc2626', '#fef2f2', '#fecaca')}>
                    <FiFileText size={15} /> {downloading === 'pdf' ? 'Exporting…' : 'PDF'}
                </button>
            </div>

            {/* Count strip */}
            {!loading && filtered.length > 0 && (
                <div style={{
                    padding: '10px 16px', background: 'linear-gradient(90deg,#f0fdfa,#f8fafc)',
                    border: '1px solid #99f6e4', borderRadius: 8, marginBottom: 12, fontSize: 13, color: '#0f766e',
                }}>
                    📋 Showing <strong>{startIndex + 1}–{Math.min(startIndex + itemsPerPage, filtered.length)}</strong> of <strong>{filtered.length.toLocaleString()}</strong> audits
                </div>
            )}

            {/* Table */}
            <div className={styles.tableWrapper}>
                <table className={styles.table} style={{ width: '100%' }}>
                    <thead>
                        <tr>
                            <th style={thStyle}>Client</th>
                            <th style={thStyle}>Source</th>
                            <th style={thStyle}>Audit Type</th>
                            <th style={thStyle}>Audit Date</th>
                            <th style={thStyle}>Auditor</th>
                            <th style={thStyle}>NC Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        {loading ? (
                            <tr><td colSpan={6} style={{ textAlign: 'center', padding: '60px' }}><EnterpriseLoader /></td></tr>
                        ) : filtered.length === 0 ? (
                            <tr>
                                <td colSpan={6} style={{ textAlign: 'center', padding: '60px' }}>
                                    <div style={{ fontSize: 36 }}>📋</div>
                                    <h3 style={{ margin: '12px 0 4px', color: '#111827' }}>No audits found</h3>
                                    <p style={{ color: '#6b7280', margin: 0 }}>No audits match your filters.</p>
                                </td>
                            </tr>
                        ) : (
                            pageRows.map((r) => (
                                <AuditStatusRow key={`${r.source}-${r.audit_kind}-${r.audit_id}`} row={r} />
                            ))
                        )}
                    </tbody>
                </table>
            </div>

            {!loading && filtered.length > 0 && (
                <Pagination
                    currentPage={currentPage}
                    setCurrentPage={setCurrentPage}
                    totalPages={totalPages}
                    startIndex={startIndex + 1}
                    endIndex={Math.min(startIndex + itemsPerPage, filtered.length)}
                    sortedDataLength={filtered.length}
                    itemsPerPage={itemsPerPage}
                    setItemsPerPage={(v: number) => { setCurrentPage(1); setItemsPerPage(v); }}
                />
            )}
        </div>
    );
}

function btn(color: string, bg: string, border: string): React.CSSProperties {
    return {
        display: 'inline-flex', alignItems: 'center', gap: 6, padding: '10px 16px',
        borderRadius: 10, border: `1px solid ${border}`, background: bg, color,
        fontSize: 13, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
    };
}