'use client';

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

const PIE_COLORS = ['#0891B2', '#059669', '#F59E0B', '#EF4444', '#8B5CF6', '#EC4899'];

export default function ReportsPage() {
  const { data: collection, isLoading: loadingCollection } = useQuery({
    queryKey: ['reports-collection'],
    queryFn: async () => (await api.get('/api/v1/reports/collection')).data,
  });

  const { data: aging, isLoading: loadingAging } = useQuery({
    queryKey: ['reports-aging'],
    queryFn: async () => (await api.get('/api/v1/reports/aging')).data,
  });

  const { data: subscribers, isLoading: loadingSubs } = useQuery({
    queryKey: ['reports-subscribers'],
    queryFn: async () => (await api.get('/api/v1/reports/subscribers')).data,
  });

  const { data: revenue, isLoading: loadingRevenue } = useQuery({
    queryKey: ['reports-revenue'],
    queryFn: async () => (await api.get('/api/v1/reports/revenue')).data,
  });

  const { data: plans, isLoading: loadingPlans } = useQuery({
    queryKey: ['reports-plans'],
    queryFn: async () => (await api.get('/api/v1/reports/plans')).data,
  });

  const collectionList = Array.isArray(collection) ? collection : [];
  const agingList = Array.isArray(aging) ? aging : [];
  const revList = Array.isArray(revenue) ? revenue : [];
  const planList = Array.isArray(plans) ? plans : [];

  // Subscribers summary
  const subSummary = subscribers ? [
    { name: 'Active', value: (subscribers as any).active ?? 0 },
    { name: 'Pending', value: (subscribers as any).pending ?? 0 },
    { name: 'Suspended', value: (subscribers as any).suspended ?? 0 },
    { name: 'Disconnected', value: (subscribers as any).disconnected ?? 0 },
  ].filter(s => s.value > 0) : [];

  return (
    <div>
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-slate-800">Reports & Analytics</h1>
        <p className="text-slate-500 text-sm mt-1">Business performance overview</p>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">

        {/* Revenue Trend */}
        <Card className="lg:col-span-2">
          <CardHeader><CardTitle className="text-base">Monthly Revenue (₱)</CardTitle></CardHeader>
          <CardContent>
            {loadingRevenue ? <Skeleton className="h-48 w-full" /> : (
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={revList}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                  <XAxis dataKey="month" tick={{ fontSize: 12 }} />
                  <YAxis tick={{ fontSize: 12 }} tickFormatter={(v) => `₱${Number(v).toLocaleString()}`} />
                  <Tooltip formatter={(v) => [`₱${Number(v).toLocaleString()}`, 'Revenue']} />
                  <Bar dataKey="totalAmount" fill="#0891B2" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Subscriber Status */}
        <Card>
          <CardHeader><CardTitle className="text-base">Subscriber Status</CardTitle></CardHeader>
          <CardContent>
            {loadingSubs ? <Skeleton className="h-48 w-full" /> : subSummary.length === 0 ? (
              <p className="text-slate-400 text-sm text-center py-8">No data</p>
            ) : (
              <ResponsiveContainer width="100%" height={200}>
                <PieChart>
                  <Pie data={subSummary} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={80} label={({ name, value }) => `${name}: ${value}`}>
                    {subSummary.map((_, i) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
                  </Pie>
                  <Tooltip />
                </PieChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Aging */}
        <Card>
          <CardHeader><CardTitle className="text-base">Invoice Aging (₱)</CardTitle></CardHeader>
          <CardContent>
            {loadingAging ? <Skeleton className="h-48 w-full" /> : agingList.length === 0 ? (
              <p className="text-slate-400 text-sm text-center py-8">No outstanding invoices</p>
            ) : (
              <ResponsiveContainer width="100%" height={200}>
                <BarChart data={agingList}>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                  <XAxis dataKey="bucket" tick={{ fontSize: 12 }} />
                  <YAxis tick={{ fontSize: 12 }} />
                  <Tooltip formatter={(v) => [`₱${Number(v).toLocaleString()}`, 'Amount']} />
                  <Bar dataKey="totalAmount" fill="#EF4444" radius={[4, 4, 0, 0]} />
                </BarChart>
              </ResponsiveContainer>
            )}
          </CardContent>
        </Card>

        {/* Collection by Collector */}
        <Card>
          <CardHeader><CardTitle className="text-base">Collection by Collector</CardTitle></CardHeader>
          <CardContent>
            {loadingCollection ? <Skeleton className="h-48 w-full" /> : collectionList.length === 0 ? (
              <p className="text-slate-400 text-sm text-center py-8">No collection data</p>
            ) : (
              <div className="space-y-3">
                {collectionList.map((c: any, i: number) => (
                  <div key={i} className="flex items-center justify-between">
                    <div>
                      <p className="text-sm font-medium text-slate-700">{c.collector}</p>
                      <p className="text-xs text-slate-400">{c.paymentCount} payments</p>
                    </div>
                    <p className="text-sm font-bold text-emerald-600">₱{Number(c.totalAmount).toLocaleString()}</p>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Plans Distribution */}
        <Card>
          <CardHeader><CardTitle className="text-base">Subscribers by Plan</CardTitle></CardHeader>
          <CardContent>
            {loadingPlans ? <Skeleton className="h-48 w-full" /> : planList.length === 0 ? (
              <p className="text-slate-400 text-sm text-center py-8">No data</p>
            ) : (
              <div className="space-y-3">
                {planList.map((p: any, i: number) => (
                  <div key={i} className="flex items-center justify-between">
                    <p className="text-sm font-medium text-slate-700">{p.planName ?? p.name ?? 'Plan ' + (i+1)}</p>
                    <div className="flex items-center gap-2">
                      <div className="w-20 bg-slate-100 rounded-full h-2">
                        <div className="h-2 rounded-full" style={{ backgroundColor: PIE_COLORS[i % PIE_COLORS.length], width: `${Math.min(100, (p.count / Math.max(...planList.map((x: any) => x.count || 1))) * 100)}%` }} />
                      </div>
                      <p className="text-sm text-slate-600">{p.count}</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </CardContent>
        </Card>

      </div>
    </div>
  );
}
