'use client';

import { useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, ArrowDownCircle, ArrowUpCircle, Settings2 } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
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 { Textarea } from '@/components/ui/textarea';
import {
  adjustBrandWallet,
  fetchBrandWallet,
  fetchBrandWalletTransactions,
} from '@/network/apis/dashboard/marketplace/wallets.apis';
import {
  FetchError,
  getErrorMessage,
} from '@/modules/marketplace-admin/components/EndpointPending';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { formatDateTime, formatMoney } from './format';

const TYPE_FILTERS = [
  { label: 'All types', value: 'all' },
  { label: 'Credit', value: 'credit' },
  { label: 'Debit', value: 'debit' },
];

const SOURCE_FILTERS = [
  { label: 'All sources', value: 'all' },
  { label: 'Top-up', value: 'top_up' },
  { label: 'Collaboration payment', value: 'collaboration_payment' },
  { label: 'Refund', value: 'refund' },
  { label: 'Admin adjustment', value: 'admin_adjustment' },
];

function safePage(raw: string | null | undefined): number {
  const n = Number(raw);
  return Number.isFinite(n) && n >= 1 ? Math.floor(n) : 1;
}

export function BrandWalletDetail({ brandId }: { brandId: number }) {
  const router = useRouter();
  const sp = useSearchParams();
  const queryClient = useQueryClient();

  const type = sp?.get('type') ?? 'all';
  const source = sp?.get('source') ?? 'all';
  const from = sp?.get('from') ?? '';
  const to = sp?.get('to') ?? '';
  const page = safePage(sp?.get('page'));

  const [adjustOpen, setAdjustOpen] = useState(false);
  const [adjustType, setAdjustType] = useState<'credit' | 'debit'>('credit');
  const [adjustAmount, setAdjustAmount] = useState('');
  const [adjustNote, setAdjustNote] = useState('');

  const txParams = useMemo(
    () => ({
      type: type === 'all' ? undefined : (type as 'credit' | 'debit'),
      source: source === 'all' ? undefined : source,
      from: from || undefined,
      to: to || undefined,
      page,
      per_page: 25,
    }),
    [type, source, from, to, page],
  );

  const updateUrl = (next: Record<string, string | null>) => {
    const p = new URLSearchParams(sp?.toString() ?? '');
    for (const [k, v] of Object.entries(next)) {
      if (!v || v === 'all') p.delete(k);
      else p.set(k, v);
    }
    if (!('page' in next)) p.delete('page');
    router.push(`?${p.toString()}`);
  };

  const walletQuery = useQuery({
    queryKey: ['brand-wallet', brandId],
    queryFn: () => fetchBrandWallet(brandId),
    retry: false,
  });

  const txQuery = useQuery({
    queryKey: ['brand-wallet-tx', brandId, txParams],
    queryFn: () => fetchBrandWalletTransactions(brandId, txParams),
    retry: false,
  });

  const adjustMutation = useMutation({
    mutationFn: () =>
      adjustBrandWallet(brandId, {
        type: adjustType,
        amount: Number(adjustAmount),
        note: adjustNote.trim(),
      }),
    onSuccess: () => {
      toast.success('Wallet balance adjusted');
      setAdjustOpen(false);
      setAdjustAmount('');
      setAdjustNote('');
      queryClient.invalidateQueries({ queryKey: ['brand-wallet', brandId] });
      queryClient.invalidateQueries({ queryKey: ['brand-wallet-tx', brandId] });
    },
    onError: (e) => toast.error(getErrorMessage(e, 'Adjustment failed')),
  });

  const wallet = walletQuery.data;
  const txItems = txQuery.data?.items ?? [];
  const txMeta = txQuery.data?.meta;

  const adjustAmountNum = Number(adjustAmount);
  const canSubmitAdjust =
    Number.isFinite(adjustAmountNum) &&
    adjustAmountNum > 0 &&
    adjustNote.trim().length >= 3 &&
    !adjustMutation.isPending;

  return (
    <div className="space-y-5">
      <Link
        href="/marketplace-admin/money/brand-wallets"
        className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="size-4" />
        Back to Brand Wallets
      </Link>

      {walletQuery.isLoading ? (
        <div className="flex items-center justify-center py-16">
          <Spinner className="size-8 animate-spin text-primary" />
        </div>
      ) : walletQuery.error ? (
        <FetchError
          error={walletQuery.error}
          fallback="Could not load this brand wallet"
        />
      ) : wallet ? (
        <>
          <div>
            <h1 className="text-2xl font-semibold">{wallet.brand_name}</h1>
            <p className="text-sm text-muted-foreground">
              Brand #{wallet.brand_id} • {wallet.brand_email}
            </p>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
            <Card>
              <CardContent className="py-5">
                <div className="text-xs uppercase tracking-wider text-muted-foreground">
                  Balance
                </div>
                <div className="mt-1 text-2xl font-semibold tabular-nums">
                  {formatMoney(wallet.balance, wallet.currency)}
                </div>
              </CardContent>
            </Card>
            <Card>
              <CardContent className="py-5">
                <div className="text-xs uppercase tracking-wider text-muted-foreground">
                  Pending in active CRs
                </div>
                <div className="mt-1 text-2xl font-semibold tabular-nums text-amber-700">
                  {formatMoney(wallet.pending, wallet.currency)}
                </div>
              </CardContent>
            </Card>
          </div>

          <Card>
            <CardContent className="flex flex-wrap items-end gap-3 py-4">
              <div className="space-y-1">
                <Label>Type</Label>
                <Select
                  value={type}
                  onValueChange={(v) => updateUrl({ type: v })}
                >
                  <SelectTrigger className="w-36">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {TYPE_FILTERS.map((o) => (
                      <SelectItem key={o.value} value={o.value}>
                        {o.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>Source</Label>
                <Select
                  value={source}
                  onValueChange={(v) => updateUrl({ source: v })}
                >
                  <SelectTrigger className="w-52">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {SOURCE_FILTERS.map((o) => (
                      <SelectItem key={o.value} value={o.value}>
                        {o.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-1">
                <Label>From</Label>
                <Input
                  type="date"
                  value={from}
                  onChange={(e) => updateUrl({ from: e.target.value || null })}
                  className="w-40"
                />
              </div>
              <div className="space-y-1">
                <Label>To</Label>
                <Input
                  type="date"
                  value={to}
                  onChange={(e) => updateUrl({ to: e.target.value || null })}
                  className="w-40"
                />
              </div>
              <div className="ml-auto">
                <Button onClick={() => setAdjustOpen(true)}>
                  <Settings2 className="size-4 mr-2" />
                  Adjust balance
                </Button>
              </div>
            </CardContent>
          </Card>

          {txQuery.isLoading ? (
            <div className="flex items-center justify-center py-16">
              <Spinner className="size-8 animate-spin text-primary" />
            </div>
          ) : txQuery.error ? (
            <FetchError
              error={txQuery.error}
              fallback="Could not load transactions"
            />
          ) : txItems.length === 0 ? (
            <Card>
              <CardContent className="py-16 text-center text-muted-foreground">
                No transactions match this filter.
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Date</TableHead>
                      <TableHead>Type</TableHead>
                      <TableHead>Source</TableHead>
                      <TableHead>Note</TableHead>
                      <TableHead>For CR</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                      <TableHead className="text-right">Balance after</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {txItems.map((t) => (
                      <TableRow key={t.id}>
                        <TableCell className="text-sm">
                          {formatDateTime(t.created_at)}
                        </TableCell>
                        <TableCell>
                          <span className="inline-flex items-center gap-1 text-xs">
                            {t.type === 'credit' ? (
                              <ArrowDownCircle className="size-3.5 text-emerald-600" />
                            ) : (
                              <ArrowUpCircle className="size-3.5 text-red-600" />
                            )}
                            {t.type}
                          </span>
                        </TableCell>
                        <TableCell className="text-sm capitalize">
                          {t.source.replace(/_/g, ' ')}
                        </TableCell>
                        <TableCell className="text-sm max-w-xs truncate">
                          {t.note ?? '—'}
                        </TableCell>
                        <TableCell className="text-sm">
                          {t.related?.type === 'collaboration_request' &&
                          t.related.id ? (
                            <Link
                              href={`/marketplace-admin/money/cr/${t.related.id}`}
                              className="hover:underline"
                            >
                              #{t.related.id}
                              {t.related.title ? ` — ${t.related.title}` : ''}
                            </Link>
                          ) : (
                            '—'
                          )}
                        </TableCell>
                        <TableCell
                          className={`text-right tabular-nums ${
                            t.type === 'credit'
                              ? 'text-emerald-700'
                              : 'text-red-700'
                          }`}
                        >
                          {t.type === 'credit' ? '+' : '−'}
                          {formatMoney(Math.abs(t.amount), t.currency)}
                        </TableCell>
                        <TableCell className="text-right tabular-nums text-muted-foreground">
                          {formatMoney(t.balance_after, t.currency)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}

          {txMeta && txMeta.last_page > 1 ? (
            <div className="flex justify-center">
              <PaginationComponent
                currentPage={txMeta.current_page}
                totalPages={txMeta.last_page}
                onPageChange={(p) => updateUrl({ page: String(p) })}
              />
            </div>
          ) : null}
        </>
      ) : null}

      <Dialog open={adjustOpen} onOpenChange={setAdjustOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Adjust wallet balance</DialogTitle>
            <DialogDescription>
              This is recorded as <code>admin_adjustment</code> in the audit
              trail and is irreversible.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="space-y-1">
              <Label>Operation</Label>
              <Select
                value={adjustType}
                onValueChange={(v) => setAdjustType(v as 'credit' | 'debit')}
              >
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="credit">Credit (add money)</SelectItem>
                  <SelectItem value="debit">Debit (remove money)</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-1">
              <Label>Amount ({wallet?.currency ?? 'SAR'})</Label>
              <Input
                type="number"
                min="0"
                step="0.01"
                value={adjustAmount}
                onChange={(e) => setAdjustAmount(e.target.value)}
                placeholder="0.00"
              />
            </div>
            <div className="space-y-1">
              <Label>
                Note <span className="text-red-500">*</span>
              </Label>
              <Textarea
                value={adjustNote}
                onChange={(e) => setAdjustNote(e.target.value)}
                rows={3}
                placeholder="e.g. Goodwill credit for failed CR #98"
              />
              <div className="text-xs text-muted-foreground">
                Required — will appear in the audit log.
              </div>
            </div>

            {canSubmitAdjust && wallet ? (
              <div className="rounded-md bg-muted/40 p-3 text-sm">
                {adjustType === 'credit' ? 'Add' : 'Remove'}{' '}
                <strong>
                  {formatMoney(adjustAmountNum, wallet.currency)}
                </strong>{' '}
                {adjustType === 'credit' ? 'to' : 'from'}{' '}
                <strong>{wallet.brand_name}</strong>'s wallet.
              </div>
            ) : null}
          </div>

          <DialogFooter>
            <Button variant="outline" onClick={() => setAdjustOpen(false)}>
              Cancel
            </Button>
            <Button
              disabled={!canSubmitAdjust}
              onClick={() => adjustMutation.mutate()}
            >
              {adjustMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : null}
              Confirm adjustment
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
