'use client';

import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import {
  CartesianGrid,
  Line,
  LineChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import {
  fetchPlatformRevenueReport,
  fetchVatReport,
} from '@/network/apis/dashboard/marketplace/wallets.apis';
import { RevenueGranularity } from '@/network/apis/dashboard/marketplace/wallets.types';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';
import { downloadCsv, firstOfMonthISO, formatDate, formatMoney, todayISO } from './format';

type ReportKind = 'platform-revenue' | 'vat-collected';

const PRESETS = [
  { label: 'This month', value: 'this_month' },
  { label: 'Last month', value: 'last_month' },
  { label: 'Last 90 days', value: 'last_90' },
  { label: 'Custom', value: 'custom' },
] as const;

type PresetValue = (typeof PRESETS)[number]['value'];

function presetRange(p: PresetValue): { from: string; to: string } | null {
  if (p === 'custom') return null;
  const today = new Date();
  const to = new Date(today);
  let from: Date;
  if (p === 'this_month') {
    from = new Date(today.getFullYear(), today.getMonth(), 1);
  } else if (p === 'last_month') {
    from = new Date(today.getFullYear(), today.getMonth() - 1, 1);
    to.setFullYear(today.getFullYear(), today.getMonth(), 0);
  } else {
    from = new Date(today);
    from.setDate(from.getDate() - 90);
  }
  const iso = (d: Date) => d.toISOString().slice(0, 10);
  return { from: iso(from), to: iso(to) };
}

export function RevenueReport({
  kind,
  title,
  description,
}: {
  kind: ReportKind;
  title: string;
  description: string;
}) {
  const [preset, setPreset] = useState<PresetValue>('this_month');
  const initial = presetRange('this_month')!;
  const [from, setFrom] = useState(initial.from);
  const [to, setTo] = useState(initial.to);
  const [groupBy, setGroupBy] = useState<RevenueGranularity>('day');

  const params = useMemo(
    () => ({ from: from || firstOfMonthISO(), to: to || todayISO(), group_by: groupBy }),
    [from, to, groupBy],
  );

  const fetcher = kind === 'platform-revenue' ? fetchPlatformRevenueReport : fetchVatReport;

  const { data, isLoading, error } = useQuery({
    queryKey: [kind, params],
    queryFn: () => fetcher(params),
    retry: false,
  });

  const series = data?.series ?? [];
  const currency = data?.currency ?? 'SAR';
  const total = data?.total ?? 0;

  const handlePreset = (p: PresetValue) => {
    setPreset(p);
    const range = presetRange(p);
    if (range) {
      setFrom(range.from);
      setTo(range.to);
    }
  };

  const handleExport = () => {
    if (!series.length) return;
    const rows: string[][] = [
      ['Date', `Amount (${currency})`],
      ...series.map((s) => [s.date, String(s.amount)]),
    ];
    downloadCsv(`${kind}-${from}_to_${to}.csv`, rows);
  };

  return (
    <div className="space-y-5">
      <div className="flex items-end justify-between gap-3 flex-wrap">
        <div>
          <h1 className="text-2xl font-semibold">{title}</h1>
          <p className="text-sm text-muted-foreground">{description}</p>
        </div>
        <Button variant="outline" onClick={handleExport} disabled={!series.length}>
          Export CSV
        </Button>
      </div>

      <Card>
        <CardContent className="space-y-4 py-4">
          <div className="flex flex-wrap gap-2">
            {PRESETS.map((p) => (
              <Button
                key={p.value}
                size="sm"
                variant={preset === p.value ? 'primary' : 'outline'}
                onClick={() => handlePreset(p.value)}
              >
                {p.label}
              </Button>
            ))}
          </div>
          <div className="flex flex-wrap items-end gap-3">
            <div className="space-y-1">
              <Label>From</Label>
              <Input
                type="date"
                value={from}
                onChange={(e) => {
                  setFrom(e.target.value);
                  setPreset('custom');
                }}
                className="w-44"
              />
            </div>
            <div className="space-y-1">
              <Label>To</Label>
              <Input
                type="date"
                value={to}
                onChange={(e) => {
                  setTo(e.target.value);
                  setPreset('custom');
                }}
                className="w-44"
              />
            </div>
            <div className="space-y-1">
              <Label>Group by</Label>
              <Select
                value={groupBy}
                onValueChange={(v) => setGroupBy(v as RevenueGranularity)}
              >
                <SelectTrigger className="w-32">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="day">Day</SelectItem>
                  <SelectItem value="week">Week</SelectItem>
                  <SelectItem value="month">Month</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {isLoading ? (
        <div className="flex items-center justify-center py-16">
          <Spinner className="size-8 animate-spin text-primary" />
        </div>
      ) : error ? (
        <FetchError error={error} fallback="Could not load report" />
      ) : (
        <>
          <Card>
            <CardContent className="py-5">
              <div className="text-xs uppercase tracking-wider text-muted-foreground">
                Total {kind === 'platform-revenue' ? 'platform revenue' : 'VAT collected'}
              </div>
              <div className="mt-1 text-3xl font-semibold tabular-nums">
                {formatMoney(total, currency)}
              </div>
              <div className="mt-1 text-xs text-muted-foreground">
                {formatDate(data?.period.from)} → {formatDate(data?.period.to)}
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardContent className="py-5">
              {series.length === 0 ? (
                <div className="text-center text-sm text-muted-foreground py-12">
                  No data points in this range.
                </div>
              ) : (
                <div className="h-[300px] w-full">
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart
                      data={series}
                      margin={{ top: 10, right: 10, left: 0, bottom: 0 }}
                    >
                      <CartesianGrid
                        strokeDasharray="3 3"
                        className="stroke-muted"
                      />
                      <XAxis
                        dataKey="date"
                        className="text-xs fill-muted-foreground"
                        tick={{ fontSize: 11 }}
                      />
                      <YAxis
                        className="text-xs fill-muted-foreground"
                        tick={{ fontSize: 11 }}
                      />
                      <Tooltip
                        contentStyle={{
                          background: 'hsl(var(--popover))',
                          border: '1px solid hsl(var(--border))',
                          borderRadius: 6,
                          fontSize: 12,
                        }}
                        formatter={(v: number) => formatMoney(v, currency)}
                      />
                      <Line
                        type="monotone"
                        dataKey="amount"
                        stroke="hsl(221, 83%, 53%)"
                        strokeWidth={2}
                        dot={false}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                </div>
              )}
            </CardContent>
          </Card>

          {series.length > 0 ? (
            <Card>
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Date</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {series.map((s) => (
                      <TableRow key={s.date}>
                        <TableCell className="text-sm">{s.date}</TableCell>
                        <TableCell className="text-right tabular-nums">
                          {formatMoney(s.amount, currency)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          ) : null}
        </>
      )}
    </div>
  );
}
