'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { Search, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Spinner } from '@/components/ui/spinners';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import PaginationComponent from '@/modules/client-management/components/paginationComponent/paginationComponent';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';
import { fetchCollabRequests } from '@/network/apis/dashboard/marketplace/collab-requests.apis';
import { formatMoney, formatDateTime } from '@/modules/marketplace-admin/money/format';
import { paymentPillClass, statusPillClass } from './utils';

const STATUS_CHIPS = [
  { label: 'All', value: '' },
  { label: 'Draft', value: 'Draft' },
  { label: 'Pending Review', value: 'Pending Review' },
  { label: 'Completed', value: 'Completed' },
];

export function CollabRequestsList() {
  const router = useRouter();
  const sp = useSearchParams();

  const status = sp?.get('status') ?? '';
  const paymentStatus = sp?.get('payment_status') ?? '';
  const brandId = sp?.get('brand_id') ?? '';
  const creatorId = sp?.get('creator_id') ?? '';
  const from = sp?.get('from') ?? '';
  const to = sp?.get('to') ?? '';
  const page = Number(sp?.get('page') ?? 1);

  const [brandIdInput, setBrandIdInput] = useState(brandId);
  const [creatorIdInput, setCreatorIdInput] = useState(creatorId);
  const [fromInput, setFromInput] = useState(from);
  const [toInput, setToInput] = useState(to);
  const [paymentInput, setPaymentInput] = useState(paymentStatus);

  useEffect(() => {
    setBrandIdInput(brandId);
    setCreatorIdInput(creatorId);
    setFromInput(from);
    setToInput(to);
    setPaymentInput(paymentStatus);
  }, [brandId, creatorId, from, to, paymentStatus]);

  const queryParams = useMemo(() => {
    const p: Record<string, unknown> = { page, per_page: 25 };
    if (status) p.status = status;
    if (paymentStatus) p.payment_status = paymentStatus;
    if (brandId) p.brand_id = brandId;
    if (creatorId) p.creator_id = creatorId;
    if (from) p.from = from;
    if (to) p.to = to;
    return p;
  }, [page, status, paymentStatus, brandId, creatorId, from, to]);

  const { data, isLoading, isFetching, error } = useQuery({
    queryKey: ['admin-collab-requests', queryParams],
    queryFn: () => fetchCollabRequests(queryParams),
    retry: false,
  });

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

  const handleApply = () =>
    updateUrl({
      brand_id: brandIdInput,
      creator_id: creatorIdInput,
      from: fromInput,
      to: toInput,
      payment_status: paymentInput,
    });

  const handleReset = () => {
    setBrandIdInput('');
    setCreatorIdInput('');
    setFromInput('');
    setToInput('');
    setPaymentInput('');
    router.push('?');
  };

  const items = data?.items ?? [];
  const meta = data?.meta;

  return (
    <div className="space-y-5">
      {/* Status chips */}
      <div className="flex flex-wrap gap-2">
        {STATUS_CHIPS.map((c) => (
          <Button
            key={c.value || 'all'}
            variant={status === c.value ? 'primary' : 'outline'}
            size="sm"
            onClick={() => updateUrl({ status: c.value || null })}
          >
            {c.label}
          </Button>
        ))}
      </div>

      {/* Filter bar */}
      <Card>
        <CardContent className="pt-4">
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-3 items-end">
            <div>
              <Label className="text-xs">Brand ID</Label>
              <Input
                value={brandIdInput}
                onChange={(e) => setBrandIdInput(e.target.value)}
                placeholder="e.g. 183"
              />
            </div>
            <div>
              <Label className="text-xs">Creator ID</Label>
              <Input
                value={creatorIdInput}
                onChange={(e) => setCreatorIdInput(e.target.value)}
                placeholder="e.g. 12"
              />
            </div>
            <div>
              <Label className="text-xs">Payment</Label>
              <Select
                value={paymentInput || 'all'}
                onValueChange={(v) => setPaymentInput(v === 'all' ? '' : v)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Any" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Any</SelectItem>
                  <SelectItem value="paid">Paid</SelectItem>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="refunded">Refunded</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <Label className="text-xs">From</Label>
              <Input
                type="date"
                value={fromInput}
                onChange={(e) => setFromInput(e.target.value)}
              />
            </div>
            <div>
              <Label className="text-xs">To</Label>
              <Input
                type="date"
                value={toInput}
                onChange={(e) => setToInput(e.target.value)}
              />
            </div>
            <div className="flex gap-2">
              <Button onClick={handleApply} className="flex-1">
                <Search className="size-4 mr-1" /> Apply
              </Button>
              <Button variant="outline" onClick={handleReset}>
                <X className="size-4" />
              </Button>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Table */}
      <Card>
        <CardContent className="p-0">
          {isLoading ? (
            <div className="flex items-center justify-center py-16">
              <Spinner className="size-8 animate-spin text-primary" />
            </div>
          ) : error ? (
            <div className="p-6">
              <FetchError
                error={error}
                fallback="Could not load collaboration requests"
              />
            </div>
          ) : items.length === 0 ? (
            <div className="py-16 text-center text-muted-foreground">
              No collaboration requests match your filters.
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>#ID</TableHead>
                  <TableHead>Name</TableHead>
                  <TableHead>Brand</TableHead>
                  <TableHead>Creator</TableHead>
                  <TableHead>Package Price</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead>Payment</TableHead>
                  <TableHead>Created</TableHead>
                  <TableHead className="text-right">Actions</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {items.map((r) => (
                  <TableRow
                    key={r.id}
                    className="cursor-pointer hover:bg-muted/40"
                    onClick={() =>
                      router.push(`/marketplace-admin/collab-requests/${r.id}`)
                    }
                  >
                    <TableCell className="font-mono text-sm">#{r.id}</TableCell>
                    <TableCell>
                      <div className="font-medium max-w-xs truncate">
                        {r.collaboration_name || '—'}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="font-medium">
                        {r.brand?.name || `Brand #${r.brand?.id ?? '?'}`}
                      </div>
                      {r.brand?.email ? (
                        <div className="text-xs text-muted-foreground">
                          {r.brand.email}
                        </div>
                      ) : null}
                    </TableCell>
                    <TableCell>
                      <div className="font-medium">
                        {r.creator?.username ||
                          `Creator #${r.creator?.id ?? '?'}`}
                      </div>
                      {r.package?.platform ? (
                        <div className="text-xs text-muted-foreground capitalize">
                          {r.package.platform}
                        </div>
                      ) : null}
                    </TableCell>
                    <TableCell className="font-medium tabular-nums">
                      {formatMoney(r.package_price ?? 0, r.currency || 'SAR')}
                    </TableCell>
                    <TableCell>
                      <span
                        className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium ${statusPillClass(r.status)}`}
                      >
                        {r.status || '—'}
                      </span>
                    </TableCell>
                    <TableCell>
                      <span
                        className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize ${paymentPillClass(r.payment_status)}`}
                      >
                        {r.payment_status || '—'}
                      </span>
                    </TableCell>
                    <TableCell className="text-sm whitespace-nowrap">
                      {formatDateTime(r.date_created)}
                    </TableCell>
                    <TableCell
                      className="text-right"
                      onClick={(e) => e.stopPropagation()}
                    >
                      <Link
                        href={`/marketplace-admin/collab-requests/${r.id}`}
                      >
                        <Button variant="outline" size="sm">
                          View
                        </Button>
                      </Link>
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>

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

      {isFetching && !isLoading ? (
        <div className="text-xs text-muted-foreground text-center">
          Refreshing…
        </div>
      ) : null}
    </div>
  );
}
