import { useState, useEffect } from 'react';
import Head from 'next/head';
import Layout from '../components/Layout';
import { scanAPI } from '../services/api';

export default function ScansPage() {
    const [scans, setScans] = useState<any[]>([]);
    const [total, setTotal] = useState(0);
    const [page, setPage] = useState(1);
    const [filters, setFilters] = useState({ marketplace: '', keyword: '', startDate: '', endDate: '' });
    const [loading, setLoading] = useState(true);

    useEffect(() => { loadScans(); }, [page, filters]);

    const loadScans = async () => {
        setLoading(true);
        try {
            const params: any = { page: String(page), limit: '15' };
            if (filters.marketplace) params.marketplace = filters.marketplace;
            if (filters.keyword) params.keyword = filters.keyword;
            if (filters.startDate) params.startDate = filters.startDate;
            if (filters.endDate) params.endDate = filters.endDate;

            const { data } = await scanAPI.getHistory(params);
            setScans(data.data.scans || []);
            setTotal(data.data.total || 0);
        } catch (err) { console.error(err); }
        setLoading(false);
    };

    const formatIDR = (n: number) => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR', maximumFractionDigits: 0 }).format(n);
    const totalPages = Math.ceil(total / 15);

    const downloadCSV = (scan: any) => {
        // Redirect to scan detail API to get items and export
        window.open(`/api/v1/scans/${scan.id}`, '_blank');
    };

    return (
        <>
            <Head><title>Scan History – MarketScope</title></Head>
            <Layout>
                <div className="animate-fade-in">
                    <h1 className="text-2xl font-bold mb-2">Scan History</h1>
                    <p className="text-gray-500 mb-6">Lihat riwayat semua scan yang pernah dilakukan</p>

                    {/* Filters */}
                    <div className="card mb-6">
                        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">Marketplace</label>
                                <select value={filters.marketplace} onChange={(e) => { setFilters({ ...filters, marketplace: e.target.value }); setPage(1); }}
                                    className="input-field text-sm">
                                    <option value="">Semua</option>
                                    <option value="SHOPEE">Shopee</option>
                                    <option value="TOKOPEDIA">Tokopedia</option>
                                    <option value="TIKTOK_SHOP">TikTok Shop</option>
                                </select>
                            </div>
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">Keyword</label>
                                <input type="text" value={filters.keyword} onChange={(e) => setFilters({ ...filters, keyword: e.target.value })}
                                    className="input-field text-sm" placeholder="Search keyword..." />
                            </div>
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">Start Date</label>
                                <input type="date" value={filters.startDate} onChange={(e) => { setFilters({ ...filters, startDate: e.target.value }); setPage(1); }}
                                    className="input-field text-sm" />
                            </div>
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">End Date</label>
                                <input type="date" value={filters.endDate} onChange={(e) => { setFilters({ ...filters, endDate: e.target.value }); setPage(1); }}
                                    className="input-field text-sm" />
                            </div>
                        </div>
                    </div>

                    {/* Table */}
                    <div className="card">
                        <div className="overflow-x-auto">
                            <table className="w-full">
                                <thead>
                                    <tr className="text-left text-xs text-gray-500 uppercase border-b border-dark-border">
                                        <th className="pb-3">Marketplace</th>
                                        <th className="pb-3">Keyword</th>
                                        <th className="pb-3">Products</th>
                                        <th className="pb-3">Min</th>
                                        <th className="pb-3">Max</th>
                                        <th className="pb-3">Avg</th>
                                        <th className="pb-3">Status</th>
                                        <th className="pb-3">Date</th>
                                        <th className="pb-3">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {scans.map((scan) => (
                                        <tr key={scan.id} className="border-b border-dark-border/50 hover:bg-dark-hover/20">
                                            <td className="py-3 pr-3"><span className="text-xs font-medium px-2 py-1 rounded bg-brand-primary/10 text-brand-primary">{scan.marketplace}</span></td>
                                            <td className="py-3 pr-3 text-sm max-w-[150px] truncate">{scan.keyword || scan.category || '-'}</td>
                                            <td className="py-3 pr-3 text-sm font-medium">{scan.totalProducts}</td>
                                            <td className="py-3 pr-3 text-sm text-green-400">{scan.minPrice ? formatIDR(scan.minPrice) : '-'}</td>
                                            <td className="py-3 pr-3 text-sm text-red-400">{scan.maxPrice ? formatIDR(scan.maxPrice) : '-'}</td>
                                            <td className="py-3 pr-3 text-sm text-blue-400">{scan.avgPrice ? formatIDR(scan.avgPrice) : '-'}</td>
                                            <td className="py-3 pr-3">
                                                <span className={`text-xs px-2 py-0.5 rounded ${scan.status === 'COMPLETED' ? 'bg-green-500/10 text-green-400' : 'bg-yellow-500/10 text-yellow-400'}`}>
                                                    {scan.status}
                                                </span>
                                            </td>
                                            <td className="py-3 pr-3 text-xs text-gray-500">{new Date(scan.createdAt).toLocaleDateString('id-ID')}</td>
                                            <td className="py-3"><button onClick={() => downloadCSV(scan)} className="text-xs text-brand-primary hover:underline">Detail</button></td>
                                        </tr>
                                    ))}
                                    {scans.length === 0 && !loading && (
                                        <tr><td colSpan={9} className="py-12 text-center text-gray-500">Tidak ada data scan</td></tr>
                                    )}
                                </tbody>
                            </table>
                        </div>

                        {/* Pagination */}
                        {totalPages > 1 && (
                            <div className="flex items-center justify-between mt-4 pt-4 border-t border-dark-border">
                                <p className="text-xs text-gray-500">Showing {(page - 1) * 15 + 1}-{Math.min(page * 15, total)} of {total}</p>
                                <div className="flex gap-2">
                                    <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="btn-secondary text-xs !py-1.5 !px-3">← Prev</button>
                                    <button disabled={page >= totalPages} onClick={() => setPage(page + 1)} className="btn-secondary text-xs !py-1.5 !px-3">Next →</button>
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </Layout>
        </>
    );
}
