'use client';

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import dealerApi from '@/lib/dealer-axios';
import { Download } from 'lucide-react';
import { formatDate } from '@/lib/dateUtils';

interface FilterForm { start_date: string; end_date: string; }

export default function DealerReportsPage() {
  const [tab, setTab] = useState<'claims' | 'by_outlet' | 'by_device' | 'sales'>('claims');
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [exporting, setExporting] = useState(false);
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const today = new Date().toISOString().slice(0, 10);
  const firstOfMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10);
  const { register, handleSubmit, getValues } = useForm<FilterForm>({ defaultValues: { start_date: firstOfMonth, end_date: today } });

  // Cache untuk menyimpan data per tab dan filter
  const [cache, setCache] = useState<Record<string, { data: any[], lastPage: number, filters: FilterForm }>>({});

  const endpointMap: Record<string, string> = {
    claims: '/dealer/report', by_outlet: '/dealer/report/by-outlet',
    by_device: '/dealer/report/by-device', sales: '/dealer/report/sales',
  };

  const getCacheKey = (tabKey: string, filters: FilterForm, pageNum: number) => {
    return `${tabKey}_${filters.start_date}_${filters.end_date}_${pageNum}`;
  };

  const load = (p: number, f: FilterForm, forceRefresh = false) => {
    const cacheKey = getCacheKey(tab, f, p);
    
    // Cek cache jika tidak force refresh
    if (!forceRefresh && cache[cacheKey]) {
      setData(cache[cacheKey].data);
      setLastPage(cache[cacheKey].lastPage);
      return;
    }

    setLoading(true);
    dealerApi.get(`${endpointMap[tab]}?page=${p}&start_date=${f.start_date}&end_date=${f.end_date}`)
      .then(r => { 
        const newData = r.data.data ?? [];
        const newLastPage = r.data.meta?.last_page ?? 1;
        
        setData(newData);
        setLastPage(newLastPage);
        
        // Simpan ke cache
        setCache(prev => ({
          ...prev,
          [cacheKey]: { data: newData, lastPage: newLastPage, filters: f }
        }));
      })
      .catch(() => {}).finally(() => setLoading(false));
  };

  const exportToExcel = async () => {
    setExporting(true);
    try {
      const f = getValues();
      const response = await dealerApi.get(`${endpointMap[tab]}/export?start_date=${f.start_date}&end_date=${f.end_date}`, {
        responseType: 'blob',
      });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      const filename = `laporan_${tab}_${f.start_date}_${f.end_date}.xlsx`;
      link.setAttribute('download', filename);
      document.body.appendChild(link);
      link.click();
      link.remove();
    } catch (err) {
      alert('Gagal export data');
    } finally {
      setExporting(false);
    }
  };

  useEffect(() => { setPage(1); load(1, getValues()); }, [tab]);
  
  const onFilter = (f: FilterForm) => { 
    setPage(1); 
    // Clear cache saat filter berubah dan force refresh
    setCache({});
    load(1, f, true); 
  };

  // Calculate summary for by_outlet and by_device
  const summary = (tab === 'by_outlet' || tab === 'by_device') ? {
    totalUnits: data.reduce((sum, row) => sum + (row.unit_terjual || 0), 0),
    totalRRP: data.reduce((sum, row) => sum + (Number(row.total_rrp) || 0), 0),
  } : null;

  const tabs = [{ key: 'claims', label: 'Semua Klaim' }, { key: 'by_outlet', label: 'Per Outlet' }, { key: 'by_device', label: 'Per Perangkat' }, { key: 'sales', label: 'Penjualan' }];

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-6">Laporan Dealer</h1>
      <form onSubmit={handleSubmit(onFilter)} className="bg-white rounded-xl shadow-sm p-4 mb-6 flex flex-wrap gap-3 items-end">
        <div><label className="block text-xs text-gray-500 mb-1">Dari</label><input {...register('start_date')} type="date" className="border rounded-lg px-3 py-2 text-sm" /></div>
        <div><label className="block text-xs text-gray-500 mb-1">Sampai</label><input {...register('end_date')} type="date" className="border rounded-lg px-3 py-2 text-sm" /></div>
        <button type="submit" className="bg-blue-700 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-800">Filter</button>
        <button type="button" onClick={exportToExcel} disabled={exporting || data.length === 0}
          className="bg-emerald-600 text-white px-4 py-2 rounded-lg text-sm hover:bg-emerald-700 disabled:opacity-50 flex items-center gap-2">
          <Download className="w-4 h-4" />
          {exporting ? 'Exporting...' : 'Export Excel'}
        </button>
      </form>

      <div className="flex gap-1 bg-gray-100 rounded-xl p-1 mb-6 w-fit flex-wrap">
        {tabs.map(t => (
          <button key={t.key} onClick={() => setTab(t.key as any)}
            className={`px-3 py-2 rounded-lg text-sm font-medium transition ${tab === t.key ? 'bg-white shadow-sm text-blue-700' : 'text-gray-500 hover:text-gray-700'}`}>
            {t.label}
          </button>
        ))}
      </div>

      {loading ? <div className="bg-white rounded-xl p-8 text-center text-gray-400 animate-pulse">Memuat...</div> : (
        <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gradient-to-r from-blue-500 to-blue-600 text-white">
                <tr>
                  {tab === 'claims' && ['Tanggal', 'Pelanggan', 'Perangkat', 'IMEI', 'Outlet', 'Status'].map(h => <th key={h} className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide">{h}</th>)}
                  {tab === 'by_outlet' && ['Outlet', 'Kota', 'Unit Terjual', 'Total Amount'].map(h => <th key={h} className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide">{h}</th>)}
                  {tab === 'by_device' && ['Perangkat', 'Brand', 'Unit Terjual', 'Total Amount'].map(h => <th key={h} className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide">{h}</th>)}
                  {tab === 'sales' && ['IMEI', 'Perangkat', 'Outlet', 'Tgl Aktivasi', 'Status'].map(h => <th key={h} className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wide">{h}</th>)}
                </tr>
              </thead>
              <tbody>
                {data.length === 0 ? <tr><td colSpan={6} className="px-4 py-8 text-center text-gray-400">Tidak ada data.</td></tr>
                : data.map((row: any, i: number) => (
                  <tr key={i} className="border-b last:border-0 hover:bg-gray-50">
                    {tab === 'claims' && <>
                      <td className="px-4 py-3 text-gray-500 whitespace-nowrap">{formatDate(row.claimed_at)}</td>
                      <td className="px-4 py-3"><p className="font-medium text-gray-800">{row.end_user?.name ?? '-'}</p><p className="text-xs text-gray-400">{row.end_user?.phone ?? ''}</p></td>
                      <td className="px-4 py-3 text-gray-700">{row.device_model ? `${row.device_model.brand} ${row.device_model.model_name}` : '-'}</td>
                      <td className="px-4 py-3 font-mono text-xs text-gray-600">{row.imei}</td>
                      <td className="px-4 py-3 text-gray-600 text-xs">{row.outlet_code ?? '-'}</td>
                      <td className="px-4 py-3"><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${row.status === 'approved' ? 'bg-green-100 text-green-700' : row.status === 'pending' ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-600'}`}>{row.status}</span></td>
                    </>}
                    {tab === 'by_outlet' && <>
                      <td className="px-4 py-3 font-medium text-gray-800">{row.outlet_name}</td>
                      <td className="px-4 py-3 text-gray-600">{row.city ?? '-'}</td>
                      <td className="px-4 py-3 text-blue-600 font-medium">{row.unit_terjual}</td>
                      <td className="px-4 py-3 text-xs font-medium text-gray-700">Rp {Number(row.total_rrp ?? 0).toLocaleString('id-ID')}</td>
                    </>}
                    {tab === 'by_device' && <>
                      <td className="px-4 py-3 font-medium text-gray-800">{row.device_name}</td>
                      <td className="px-4 py-3 text-gray-600">{row.brand}</td>
                      <td className="px-4 py-3 text-blue-600 font-medium">{row.unit_terjual}</td>
                      <td className="px-4 py-3 text-xs font-medium text-gray-700">Rp {Number(row.total_rrp ?? 0).toLocaleString('id-ID')}</td>
                    </>}
                    {tab === 'sales' && <>
                      <td className="px-4 py-3 font-mono text-xs text-gray-600">{row.imei}</td>
                      <td className="px-4 py-3 font-medium text-gray-800">{row.device_name}</td>
                      <td className="px-4 py-3 text-gray-600 text-xs">{row.outlet_id ?? '-'}</td>
                      <td className="px-4 py-3 text-gray-600 whitespace-nowrap">{formatDate(row.activation_date)}</td>
                      <td className="px-4 py-3"><span className={`text-xs px-2 py-0.5 rounded-full font-medium ${row.validation_status === 'valid' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'}`}>{row.validation_status}</span></td>
                    </>}
                  </tr>
                ))}
              </tbody>
              {summary && data.length > 0 && (
                <tfoot className="bg-gradient-to-r from-blue-50 to-indigo-50 border-t-2 border-blue-200">
                  <tr className="font-bold">
                    <td className="px-4 py-4 text-gray-800" colSpan={2}>TOTAL</td>
                    <td className="px-4 py-4 text-blue-700 text-base">{summary.totalUnits.toLocaleString('id-ID')}</td>
                    <td className="px-4 py-4 text-emerald-700 text-base">Rp {summary.totalRRP.toLocaleString('id-ID')}</td>
                  </tr>
                </tfoot>
              )}
            </table>
          </div>
          {lastPage > 1 && (
            <div className="flex justify-center gap-2 p-4">
              <button onClick={() => { const newPage = page - 1; setPage(newPage); load(newPage, getValues()); }} disabled={page === 1} className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40">← Sebelumnya</button>
              <span className="px-3 py-1.5 text-sm text-gray-500">{page} / {lastPage}</span>
              <button onClick={() => { const newPage = page + 1; setPage(newPage); load(newPage, getValues()); }} disabled={page >= lastPage} className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40">Berikutnya →</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
