'use client';

import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer, Cell } from 'recharts';

const peso = (v: number) => '₱' + (v ?? 0).toLocaleString('en-PH', { minimumFractionDigits: 2 });

export default function ReportsPage() {
  const [from, setFrom] = useState(() => {
    const d = new Date();
    d.setDate(1);
    return d.toISOString().split('T')[0];
  });
  const [to, setTo] = useState(() => new Date().toISOString().split('T')[0]);

  const { data: collection, isLoading: collLoading } = useQuery({
    queryKey: ['reports', 'collection', from, to],
    queryFn: async () => {
      const res = await api.get(`/api/v1/reports/collection?from=${from}&to=${to}`);
      return res.data as Array<{ collector: string; totalAmount: number; paymentCount: number }>;
    },
  });

  const { data: aging, isLoading: agingLoading } = useQuery({
    queryKey: ['reports', 'aging'],
    queryFn: async () => {
      const res = await api.get('/api/v1/reports/aging');
      return res.data as Array<{ bucket: string; invoiceCount: number; totalAmount: number }>;
    },
  });

  const { data: subscribers, isLoading: subLoading } = useQuery({
    queryKey: ['reports', 'subscribers'],
    queryFn: async () => {
      const res = await api.get('/api/v1/reports/subscribers');
      return res.data as Array<{ plan: string; count: number; revenue: number }>;
    },
  });

  const { data: revenue, isLoading: revLoading } = useQuery({
    queryKey: ['reports', 'revenue'],
    queryFn: async () => {
      const res = await api.get('/api/v1/reports/revenue');
      return res.data as Array<{ month: string; total: number }>;
    },
  });

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-800">Reports</h1>
        <p className="text-slate-500 text-sm mt-1">Financial and operational analytics</p>
      </div>

      {/* Collection Report */}
      <Card className="border shadow-sm mb-6">
        <CardHeader className="flex flex-row items-center justify-between pb-3">
          <CardTitle className="text-base font-semibold text-slate-700">Collection Report</CardTitle>
          <div className="flex gap-2 items-center">
            <input type="date" value={from} onChange={(e) => setFrom(e.target.value)}
              className="border rounded-md px-2 py-1 text-sm text-slate-700" />
            <span className="text-slate-400 text-sm">to</span>
            <input type="date" value={to} onChange={(e) => setTo(e.target.value)}
              className="border rounded-md px-2 py-1 text-sm text-slate-700" />
          </div>
        </CardHeader>
        <CardContent>
          {collLoading ? (
            <Skeleton className="h-32 w-full" />
          ) : !collection?.length ? (
            <p className="text-center text-slate-400 py-6">No collections in this period</p>
          ) : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-2 font-medium text-slate-500">Collector</th>
                  <th className="text-right py-2 font-medium text-slate-500">Payments</th>
                  <th className="text-right py-2 font-medium text-slate-500">Total</th>
                </tr>
              </thead>
              <tbody>
                {collection?.map((row, i) => (
                  <tr key={i} className="border-b">
                    <td className="py-2 text-slate-700">{row.collector}</td>
                    <td className="py-2 text-right text-slate-600">{row.paymentCount}</td>
                    <td className="py-2 text-right font-semibold text-slate-800">{peso(row.totalAmount)}</td>
                  </tr>
                ))}
                <tr className="bg-slate-50">
                  <td className="py-2 font-semibold text-slate-700">Total</td>
                  <td className="py-2 text-right font-semibold text-slate-700">
                    {collection?.reduce((s, r) => s + r.paymentCount, 0)}
                  </td>
                  <td className="py-2 text-right font-semibold text-slate-800">
                    {peso(collection?.reduce((s, r) => s + r.totalAmount, 0) ?? 0)}
                  </td>
                </tr>
              </tbody>
            </table>
          )}
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-6">
        {/* Revenue Trend */}
        <Card className="border shadow-sm">
          <CardHeader>
            <CardTitle className="text-base font-semibold text-slate-700">Revenue Trend (12 months)</CardTitle>
          </CardHeader>
          <CardContent>
            {revLoading ? <Skeleton className="h-48 w-full" /> : (
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={revenue ?? []}>
                  <XAxis dataKey="month" tick={{ fontSize: 11 }} />
                  <YAxis tick={{ fontSize: 11 }} tickFormatter={(v) => `₱${(v/1000).toFixed(0)}k`} />
                  <Tooltip formatter={(v: any) => peso(v)} />
                  <Bar dataKey="total" fill="#0891B2" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Aging */}
        <Card className="border shadow-sm">
          <CardHeader>
            <CardTitle className="text-base font-semibold text-slate-700">Accounts Receivable Aging</CardTitle>
          </CardHeader>
          <CardContent>
            {agingLoading ? <Skeleton className="h-48 w-full" /> : (
              <div className="space-y-3">
                {aging?.map((bucket) => (
                  <div key={bucket.bucket} className="flex items-center gap-3">
                    <span className="text-sm text-slate-500 w-16">{bucket.bucket}d</span>
                    <div className="flex-1 bg-slate-100 rounded-full h-3 overflow-hidden">
                      <div
                        className="h-3 rounded-full"
                        style={{
                          width: `${Math.min(100, (bucket.totalAmount / (Math.max(...(aging?.map(b => b.totalAmount) ?? [1])) || 1)) * 100)}%`,
                          backgroundColor: bucket.bucket === '90+' ? '#DC2626' : bucket.bucket === '61-90' ? '#D97706' : '#0891B2',
                        }}
                      />
                    </div>
                    <span className="text-sm font-medium text-slate-700 w-32 text-right">{peso(bucket.totalAmount)}</span>
                    <span className="text-xs text-slate-400 w-16 text-right">{bucket.invoiceCount} inv</span>
                  </div>
                ))}
                {!aging?.some(b => b.totalAmount > 0) && (
                  <p className="text-center text-slate-400 py-6">No overdue invoices 🎉</p>
                )}
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Subscribers by Plan */}
      <Card className="border shadow-sm">
        <CardHeader>
          <CardTitle className="text-base font-semibold text-slate-700">Subscribers by Plan</CardTitle>
        </CardHeader>
        <CardContent>
          {subLoading ? <Skeleton className="h-32 w-full" /> : (
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="text-left py-2 font-medium text-slate-500">Plan</th>
                  <th className="text-right py-2 font-medium text-slate-500">Subscribers</th>
                  <th className="text-right py-2 font-medium text-slate-500">Monthly Revenue</th>
                </tr>
              </thead>
              <tbody>
                {(subscribers as any[])?.map((row: any, i: number) => (
                  <tr key={i} className="border-b">
                    <td className="py-2 text-slate-700">{row.plan ?? row.name ?? '—'}</td>
                    <td className="py-2 text-right text-slate-600">{row.count ?? row.subscribers ?? 0}</td>
                    <td className="py-2 text-right font-semibold text-slate-800">
                      {peso(row.revenue ?? row.monthlyRevenue ?? 0)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
