'use client';

import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import outletApi from '@/lib/outlet-axios';
import { formatDate } from '@/lib/dateUtils';

interface FilterForm { start_date: string; end_date: string; }

interface ClaimRow {
  id: number;
  imei: string;
  status: string;
  claimed_at: string;
  end_user?: { name: string; phone: string };
  device_model?: { model_name: string; brand: string };
  promotion?: { name: string; reward_method: string };
}

interface DeviceRow {
  device_name: string;
  brand: string;
  unit_terjual: number;
  total_claims: number;
  approved_claims: number;
  claim_rate: number;
}

interface SalesRow {
  id: number;
  imei: string;
  device_name: string;
  device_model: string;
  activation_date: string;
  validation_status: string;
}

const statusColor: Record<string, string> = {
  pending: 'bg-yellow-100 text-yellow-700',
  approved: 'bg-green-100 text-green-700',
  rejected: 'bg-red-100 text-red-700',
};

const validationColor: Record<string, string> = {
  valid:   'bg-green-100 text-green-700',
  invalid: 'bg-red-100 text-red-700',
  pending: 'bg-yellow-100 text-yellow-700',
};

export default function OutletReportsPage() {
  const [tab, setTab] = useState<'claims' | 'by_device' | 'sales'>('claims');
  const [claims, setClaims] = useState<ClaimRow[]>([]);
  const [devices, setDevices] = useState<DeviceRow[]>([]);
  const [sales, setSales] = useState<SalesRow[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [lastPage, setLastPage] = useState(1);
  const [salesPage, setSalesPage] = useState(1);
  const [salesLastPage, setSalesLastPage] = 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 },
  });

  const loadClaims = (p: number, filters: FilterForm) => {
    setLoading(true);
    outletApi.get(`/outlet/report?page=${p}&start_date=${filters.start_date}&end_date=${filters.end_date}`)
      .then((r) => {
        setClaims(r.data.data ?? []);
        setLastPage(r.data.meta?.last_page ?? 1);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  const loadDevices = (filters: FilterForm) => {
    setLoading(true);
    outletApi.get(`/outlet/report/by-device?start_date=${filters.start_date}&end_date=${filters.end_date}`)
      .then((r) => setDevices(r.data.data ?? []))
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  const loadSales = (p: number, filters: FilterForm) => {
    setLoading(true);
    outletApi.get(`/outlet/report/sales?page=${p}&start_date=${filters.start_date}&end_date=${filters.end_date}`)
      .then((r) => {
        setSales(r.data.data ?? []);
        setSalesLastPage(r.data.meta?.last_page ?? 1);
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    const f = getValues();
    if (tab === 'claims') loadClaims(1, f);
    else if (tab === 'by_device') loadDevices(f);
    else loadSales(1, f);
  }, [tab]);

  const onFilter = (data: FilterForm) => {
    setPage(1);
    setSalesPage(1);
    if (tab === 'claims') loadClaims(1, data);
    else if (tab === 'by_device') loadDevices(data);
    else loadSales(1, data);
  };

  return (
    <div>
      <h1 className="text-xl font-bold text-gray-800 mb-6">Laporan Outlet</h1>

      {/* Filter */}
      <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 Tanggal</label>
          <input {...register('start_date')} type="date"
            className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
        <div>
          <label className="block text-xs text-gray-500 mb-1">Sampai Tanggal</label>
          <input {...register('end_date')} type="date"
            className="border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500" />
        </div>
        <button type="submit" className="bg-blue-700 text-white px-4 py-2 rounded-lg text-sm hover:bg-blue-800">
          Filter
        </button>
      </form>

      {/* Tabs */}
      <div className="flex gap-1 bg-gray-100 rounded-xl p-1 mb-6 w-fit">
        {(['claims', 'by_device', 'sales'] as const).map((t) => (
          <button key={t} onClick={() => setTab(t)}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition ${tab === t ? 'bg-white shadow-sm text-blue-700' : 'text-gray-500 hover:text-gray-700'}`}>
            {t === 'claims' ? 'Semua Klaim' : t === 'by_device' ? 'Per Perangkat' : 'Penjualan'}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="bg-white rounded-xl p-8 text-center text-gray-400 animate-pulse">Memuat data...</div>
      ) : tab === 'claims' ? (
        <>
          <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-gray-50 border-b">
                  <tr>
                    {['Tanggal', 'Pelanggan', 'Perangkat', 'IMEI', 'Promosi', 'Status'].map((h) => (
                      <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500">{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {claims.length === 0 ? (
                    <tr><td colSpan={6} className="px-4 py-8 text-center text-gray-400">Tidak ada data.</td></tr>
                  ) : claims.map((c) => (
                    <tr key={c.id} className="border-b last:border-0 hover:bg-gray-50">
                      <td className="px-4 py-3 text-gray-500 whitespace-nowrap">
                        {formatDate(c.claimed_at)}
                      </td>
                      <td className="px-4 py-3">
                        <p className="font-medium text-gray-800">{c.end_user?.name ?? '-'}</p>
                        <p className="text-xs text-gray-400">{c.end_user?.phone ?? ''}</p>
                      </td>
                      <td className="px-4 py-3 text-gray-700">
                        {c.device_model ? `${c.device_model.brand} ${c.device_model.model_name}` : '-'}
                      </td>
                      <td className="px-4 py-3 font-mono text-xs text-gray-600">{c.imei}</td>
                      <td className="px-4 py-3 text-gray-700">{c.promotion?.name ?? '-'}</td>
                      <td className="px-4 py-3">
                        <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${statusColor[c.status] ?? 'bg-gray-100 text-gray-600'}`}>
                          {c.status}
                        </span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>

          {lastPage > 1 && (
            <div className="flex justify-center gap-2 mt-4">
              <button onClick={() => { setPage((p) => p - 1); loadClaims(page - 1, getValues()); }} disabled={page === 1}
                className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40 hover:bg-gray-50">← Sebelumnya</button>
              <span className="px-3 py-1.5 text-sm text-gray-500">{page} / {lastPage}</span>
              <button onClick={() => { setPage((p) => p + 1); loadClaims(page + 1, getValues()); }} disabled={page === lastPage}
                className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40 hover:bg-gray-50">Berikutnya →</button>
            </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-gray-50 border-b">
                <tr>
                  {['#', 'Perangkat', 'Brand', 'Unit Terjual', 'Total Klaim', 'Disetujui', 'Claim Rate'].map((h) => (
                    <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {devices.length === 0 ? (
                  <tr><td colSpan={6} className="px-4 py-8 text-center text-gray-400">Tidak ada data.</td></tr>
                ) : devices.map((d, i) => (
                  <tr key={i} className="border-b last:border-0 hover:bg-gray-50">
                    <td className="px-4 py-3 text-gray-400">{i + 1}</td>
                    <td className="px-4 py-3 font-medium text-gray-800">{d.device_name}</td>
                    <td className="px-4 py-3 text-gray-600">{d.brand}</td>
                    <td className="px-4 py-3 text-blue-600 font-medium">{d.unit_terjual.toLocaleString('id-ID')}</td>
                    <td className="px-4 py-3 text-gray-700">{d.total_claims}</td>
                    <td className="px-4 py-3">
                      <span className="bg-green-100 text-green-700 px-2 py-0.5 rounded-full text-xs font-medium">
                        {d.approved_claims}
                      </span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs font-medium ${d.claim_rate >= 70 ? 'text-green-600' : d.claim_rate >= 40 ? 'text-yellow-600' : 'text-red-500'}`}>
                        {d.claim_rate}%
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Sales Tab */}
      {tab === 'sales' && (
        <div className="bg-white rounded-2xl shadow-sm overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="bg-gray-50 border-b">
                <tr>
                  {['#', 'IMEI', 'Perangkat', 'Tgl Aktivasi', 'Status Validasi'].map((h) => (
                    <th key={h} className="px-4 py-3 text-left text-xs font-medium text-gray-500">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {loading ? (
                  <tr><td colSpan={5} className="px-4 py-8 text-center text-gray-400 animate-pulse">Memuat data...</td></tr>
                ) : sales.length === 0 ? (
                  <tr><td colSpan={5} className="px-4 py-8 text-center text-gray-400">Tidak ada data penjualan.</td></tr>
                ) : sales.map((s, i) => (
                  <tr key={s.id} className="border-b last:border-0 hover:bg-gray-50">
                    <td className="px-4 py-3 text-gray-400">{((salesPage - 1) * 50) + i + 1}</td>
                    <td className="px-4 py-3 font-mono text-xs text-gray-600">{s.imei}</td>
                    <td className="px-4 py-3 font-medium text-gray-800">{s.device_name}</td>
                    <td className="px-4 py-3 text-gray-600 whitespace-nowrap">
                      {formatDate(s.activation_date)}
                    </td>
                    <td className="px-4 py-3">
                      <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${validationColor[s.validation_status] ?? 'bg-gray-100 text-gray-500'}`}>
                        {s.validation_status}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {salesLastPage > 1 && (
            <div className="flex justify-center gap-2 p-4">
              <button onClick={() => { setSalesPage((p) => p - 1); loadSales(salesPage - 1, getValues()); }} disabled={salesPage === 1}
                className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40 hover:bg-gray-50">← Sebelumnya</button>
              <span className="px-3 py-1.5 text-sm text-gray-500">{salesPage} / {salesLastPage}</span>
              <button onClick={() => { setSalesPage((p) => p + 1); loadSales(salesPage + 1, getValues()); }} disabled={salesPage >= salesLastPage}
                className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40 hover:bg-gray-50">Berikutnya →</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
