'use client';

import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { ArrowLeft } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Spinner } from '@/components/ui/spinners';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { fetchCrTransfers } from '@/network/apis/dashboard/marketplace/wallets.apis';
import {
  CrTransferLine,
  LedgerAccountType,
} from '@/network/apis/dashboard/marketplace/wallets.types';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';
import { formatDateTime, formatMoney } from './format';

const ACCOUNT_BADGE: Record<LedgerAccountType, string> = {
  creator: 'bg-blue-100 text-blue-700 border-blue-200',
  platform: 'bg-emerald-100 text-emerald-700 border-emerald-200',
  vat: 'bg-amber-100 text-amber-800 border-amber-200',
};

function accountLabel(line: CrTransferLine): string {
  if (line.account_type === 'creator') {
    return line.creator_name ?? `Creator #${line.account_id}`;
  }
  if (line.account_type === 'platform') return 'Platform';
  if (line.account_type === 'vat') return 'VAT payable';
  return '—';
}

function statusBadgeClass(status?: string | null): string {
  const s = (status ?? '').toLowerCase();
  if (s === 'completed' || s === 'paid') return 'bg-emerald-100 text-emerald-700 border-emerald-200';
  if (s === 'cancelled' || s === 'rejected') return 'bg-red-100 text-red-700 border-red-200';
  if (s === 'pending' || s === 'in_progress') return 'bg-amber-100 text-amber-800 border-amber-200';
  return 'bg-muted/40 text-muted-foreground border-border';
}

export function CrMoneyFlow({ crId }: { crId: number }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ['cr-transfers', crId],
    queryFn: () => fetchCrTransfers(crId),
    retry: false,
  });

  const cr = data?.collaboration_request;
  const brandPaid = data?.brand_paid;
  const transfers = data?.transfers ?? [];
  const summary = data?.summary;
  const currency = summary?.currency ?? brandPaid?.currency ?? transfers[0]?.currency ?? 'SAR';

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

      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <h1 className="text-2xl font-semibold">
            Collaboration #{crId}
            {cr?.title ? <span className="text-muted-foreground"> — {cr.title}</span> : null}
          </h1>
          <p className="text-sm text-muted-foreground">
            {cr?.brand_id && cr?.brand_name ? (
              <>
                Brand:{' '}
                <Link
                  href={`/marketplace-admin/money/brand-wallets/${cr.brand_id}`}
                  className="text-foreground hover:underline"
                >
                  {cr.brand_name}
                </Link>
                {' · '}
              </>
            ) : null}
            Money flow for this collaboration request.
          </p>
        </div>
        {cr?.status ? (
          <span
            className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-medium capitalize ${statusBadgeClass(cr.status)}`}
          >
            {cr.status}
          </span>
        ) : null}
      </div>

      {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 transfers for this CR"
        />
      ) : (
        <>
          {summary ? (
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
              <Card>
                <CardContent className="py-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    Brand pay-in
                  </div>
                  <div className="mt-1 text-xl font-semibold tabular-nums">
                    {formatMoney(summary.brand_paid, currency)}
                  </div>
                  {brandPaid?.paid_at ? (
                    <div className="mt-0.5 text-xs text-muted-foreground">
                      {formatDateTime(brandPaid.paid_at)}
                    </div>
                  ) : null}
                </CardContent>
              </Card>
              <Card>
                <CardContent className="py-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    Creator earned
                  </div>
                  <div className="mt-1 text-xl font-semibold tabular-nums text-blue-700">
                    {formatMoney(summary.creator_earned, currency)}
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="py-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    Platform fee
                  </div>
                  <div className="mt-1 text-xl font-semibold tabular-nums text-emerald-700">
                    {formatMoney(summary.platform_fee, currency)}
                  </div>
                </CardContent>
              </Card>
              <Card>
                <CardContent className="py-4">
                  <div className="text-xs uppercase tracking-wider text-muted-foreground">
                    VAT collected
                  </div>
                  <div className="mt-1 text-xl font-semibold tabular-nums text-amber-700">
                    {formatMoney(summary.vat_collected, currency)}
                  </div>
                </CardContent>
              </Card>
            </div>
          ) : null}

          {brandPaid === null && transfers.length === 0 ? (
            <Card>
              <CardContent className="py-10 text-center text-sm text-muted-foreground">
                {cr?.status && cr.status.toLowerCase() !== 'completed'
                  ? 'No transfers yet — collaboration is not completed.'
                  : 'No transfers recorded for this CR.'}
              </CardContent>
            </Card>
          ) : transfers.length === 0 ? (
            <Card>
              <CardContent className="py-10 text-center text-sm text-muted-foreground">
                Brand has paid but no creator/platform/VAT transfers recorded yet.
              </CardContent>
            </Card>
          ) : (
            <Card>
              <CardContent className="p-0">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Posted</TableHead>
                      <TableHead>Account</TableHead>
                      <TableHead>Account name</TableHead>
                      <TableHead>Type</TableHead>
                      <TableHead className="text-right">Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {transfers.map((t, idx) => (
                      <TableRow key={`${t.account_type}-${t.account_id}-${idx}`}>
                        <TableCell className="text-sm whitespace-nowrap">
                          {formatDateTime(t.posted_at)}
                        </TableCell>
                        <TableCell>
                          <span
                            className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize ${
                              ACCOUNT_BADGE[t.account_type] ?? ''
                            }`}
                          >
                            {t.account_type}
                          </span>
                        </TableCell>
                        <TableCell className="text-sm">
                          {accountLabel(t)}
                        </TableCell>
                        <TableCell className="text-sm capitalize">
                          {t.type}
                        </TableCell>
                        <TableCell
                          className={`text-right tabular-nums ${
                            t.type === 'credit'
                              ? 'text-emerald-700'
                              : 'text-red-700'
                          }`}
                        >
                          {t.type === 'credit' ? '+' : '−'}
                          {formatMoney(Math.abs(Number(t.amount)), t.currency)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </CardContent>
            </Card>
          )}
        </>
      )}
    </div>
  );
}
