'use client';

import { useState } from 'react';
import Link from 'next/link';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import {
  ArrowLeft,
  CheckCircle2,
  ExternalLink,
  ShieldCheck,
  Wallet as WalletIcon,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Spinner } from '@/components/ui/spinners';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  adminApproveSubmission,
  fetchCollabRequest,
  fetchCollabRequestSubmissions,
} from '@/network/apis/dashboard/marketplace/collab-requests.apis';
import type { CrSubmission } from '@/network/apis/dashboard/marketplace/collab-requests.types';
import { formatMoney, formatDateTime } from '@/modules/marketplace-admin/money/format';
import { FetchError } from '@/modules/marketplace-admin/components/EndpointPending';
import {
  canAdminOverride,
  paymentPillClass,
  resolveMediaUrl,
  statusPillClass,
} from './utils';

export function CollabRequestDetail({ crId }: { crId: number }) {
  const queryClient = useQueryClient();
  const [overrideTarget, setOverrideTarget] = useState<CrSubmission | null>(
    null,
  );
  const [overrideReason, setOverrideReason] = useState('');
  const [adminNotes, setAdminNotes] = useState('');
  const [fieldError, setFieldError] = useState<string | null>(null);

  const detail = useQuery({
    queryKey: ['admin-collab-request', crId],
    queryFn: () => fetchCollabRequest(crId),
    retry: false,
  });

  const submissions = useQuery({
    queryKey: ['admin-collab-request-submissions', crId],
    queryFn: () => fetchCollabRequestSubmissions(crId),
    retry: false,
  });

  const closeOverride = () => {
    setOverrideTarget(null);
    setOverrideReason('');
    setAdminNotes('');
    setFieldError(null);
  };

  const overrideMutation = useMutation({
    mutationFn: (submissionId: number) =>
      adminApproveSubmission(crId, submissionId, {
        override_reason: overrideReason.trim() || undefined,
        admin_notes: adminNotes.trim() || undefined,
      }),
    onSuccess: () => {
      toast.success(
        'Submission admin-approved. Funds released to creator wallet.',
      );
      queryClient.invalidateQueries({
        queryKey: ['admin-collab-request', crId],
      });
      queryClient.invalidateQueries({
        queryKey: ['admin-collab-request-submissions', crId],
      });
      queryClient.invalidateQueries({ queryKey: ['admin-collab-requests'] });
      closeOverride();
    },
    onError: (e: unknown) => {
      const resp = (
        e as {
          response?: {
            data?: {
              message?: string;
              errors?: Record<string, string[]>;
            };
          };
        }
      )?.response?.data;
      const fieldMsg =
        resp?.errors?.override_reason?.[0] ||
        resp?.errors?.admin_notes?.[0];
      if (fieldMsg) {
        setFieldError(fieldMsg);
        toast.error(fieldMsg);
        return;
      }
      toast.error(resp?.message || 'Failed to approve submission');
    },
  });

  if (detail.isLoading) {
    return (
      <div className="flex items-center justify-center py-16">
        <Spinner className="size-8 animate-spin text-primary" />
      </div>
    );
  }

  if (detail.error) {
    return (
      <div className="p-6">
        <FetchError
          error={detail.error}
          fallback="Could not load this collaboration request"
        />
      </div>
    );
  }

  const cr = detail.data;
  if (!cr) return null;

  const subs = submissions.data ?? [];
  const currency = cr.currency || 'SAR';

  return (
    <div className="space-y-6">
      <div className="flex items-center gap-3">
        <Link href="/marketplace-admin/collab-requests">
          <Button variant="outline" size="sm">
            <ArrowLeft className="size-4 mr-1" /> Back
          </Button>
        </Link>
        <div className="text-sm text-muted-foreground">
          Collaboration Request <span className="font-mono">#{cr.id}</span>
        </div>
      </div>

      {/* Header */}
      <Card>
        <CardContent className="pt-6 space-y-4">
          <div className="flex flex-wrap items-start justify-between gap-3">
            <div>
              <h2 className="text-xl font-semibold">
                {cr.collaboration_name || 'Untitled collaboration'}
              </h2>
              <div className="text-xs text-muted-foreground mt-1">
                Created {formatDateTime(cr.date_created)}
              </div>
            </div>
            <div className="flex gap-2">
              <span
                className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium ${statusPillClass(cr.status)}`}
              >
                {cr.status}
              </span>
              <span
                className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize ${paymentPillClass(cr.payment_status)}`}
              >
                {cr.payment_status || '—'}
              </span>
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pt-2">
            <div>
              <div className="text-xs text-muted-foreground">Brand</div>
              <Link
                href={
                  cr.brand?.id
                    ? `/marketplace-admin/money/brand-wallets/${cr.brand.id}`
                    : '#'
                }
                className="text-sm font-medium hover:underline"
              >
                {cr.brand?.name || `Brand #${cr.brand?.id ?? '?'}`}
              </Link>
              {cr.brand?.email ? (
                <div className="text-xs text-muted-foreground">
                  {cr.brand.email}
                </div>
              ) : null}
            </div>
            <div>
              <div className="text-xs text-muted-foreground">Creator</div>
              <div className="text-sm font-medium">
                {cr.creator?.username ||
                  `Creator #${cr.creator?.id ?? '?'}`}
              </div>
              {cr.package?.platform ? (
                <div className="text-xs text-muted-foreground capitalize">
                  {cr.package.platform}
                </div>
              ) : null}
            </div>
            <div>
              <div className="text-xs text-muted-foreground">Package price</div>
              <div className="text-sm font-medium tabular-nums">
                {formatMoney(cr.package_price ?? 0, currency)}
              </div>
            </div>
            <div>
              <div className="text-xs text-muted-foreground">Wallet used</div>
              <div className="text-sm font-medium tabular-nums">
                {formatMoney(cr.wallet_used ?? 0, currency)}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Money snapshot */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base flex items-center gap-2">
            <WalletIcon className="size-4" /> Money breakdown
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <Stat
              label="Total amount"
              value={formatMoney(cr.total_amount ?? 0, currency)}
            />
            <Stat
              label="Platform fee"
              value={formatMoney(cr.platform_fee ?? 0, currency)}
              hint={
                cr.platform_fee_rate
                  ? `${cr.platform_fee_rate}%`
                  : undefined
              }
            />
            <Stat
              label="VAT"
              value={formatMoney(cr.vat_amount ?? 0, currency)}
              hint={cr.vat_rate ? `${cr.vat_rate}%` : undefined}
            />
            <Stat
              label="Discount"
              value={formatMoney(cr.discount_amount ?? 0, currency)}
            />
          </div>
          <div className="mt-4 flex flex-wrap gap-3 text-xs text-muted-foreground">
            <Link
              href={`/marketplace-admin/money/cr/${cr.id}`}
              className="text-primary hover:underline inline-flex items-center gap-1"
            >
              View full money flow <ExternalLink className="size-3" />
            </Link>
            {cr.paid_at ? <span>· Paid {formatDateTime(cr.paid_at)}</span> : null}
            {cr.completed_at ? (
              <span>· Completed {formatDateTime(cr.completed_at)}</span>
            ) : null}
          </div>
        </CardContent>
      </Card>

      {/* Submissions */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">
            Content submissions{' '}
            <span className="text-muted-foreground font-normal">
              ({subs.length})
            </span>
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {submissions.isLoading ? (
            <div className="py-8 flex justify-center">
              <Spinner className="size-6 animate-spin text-primary" />
            </div>
          ) : submissions.error ? (
            <FetchError
              error={submissions.error}
              fallback="Could not load submissions"
            />
          ) : subs.length === 0 ? (
            <div className="py-10 text-center text-sm text-muted-foreground">
              No submissions have been uploaded yet.
            </div>
          ) : (
            subs.map((s) => (
              <SubmissionCard
                key={s.id}
                submission={s}
                onAdminApprove={() => {
                  setOverrideTarget(s);
                  setOverrideReason('');
                  setAdminNotes('');
                  setFieldError(null);
                }}
              />
            ))
          )}
        </CardContent>
      </Card>

      {/* Override dialog */}
      <Dialog
        open={!!overrideTarget}
        onOpenChange={(o) => !o && closeOverride()}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <ShieldCheck className="size-5 text-amber-600" />
              Admin-approve submission #{overrideTarget?.id}?
            </DialogTitle>
            <DialogDescription>
              This overrides the brand's review and{' '}
              <strong>releases the escrowed funds to the creator's wallet</strong>.
              Use this only when the brand is unresponsive or wrongly refusing
              valid content. The action is recorded in the audit log.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3 py-2">
            <div>
              <label
                htmlFor="override-reason"
                className="text-sm font-medium text-zinc-700"
              >
                Override reason{' '}
                <span className="text-zinc-400">(brand-visible)</span>
              </label>
              <textarea
                id="override-reason"
                value={overrideReason}
                onChange={(e) => {
                  setOverrideReason(e.target.value.slice(0, 1000));
                  if (fieldError) setFieldError(null);
                }}
                maxLength={1000}
                rows={3}
                placeholder="e.g., Content meets brief; brand has been unresponsive for 7 days."
                className="w-full rounded-md border border-zinc-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-amber-500 focus:border-amber-500 mt-1"
                disabled={overrideMutation.isPending}
              />
              <div className="text-xs text-zinc-500 text-right">
                {overrideReason.length}/1000
              </div>
              {fieldError ? (
                <div className="text-xs text-red-600">{fieldError}</div>
              ) : null}
            </div>
            <div>
              <label
                htmlFor="override-admin-notes"
                className="text-sm font-medium text-zinc-700"
              >
                Internal notes <span className="text-zinc-400">(optional)</span>
              </label>
              <textarea
                id="override-admin-notes"
                value={adminNotes}
                onChange={(e) => setAdminNotes(e.target.value.slice(0, 1000))}
                maxLength={1000}
                rows={2}
                placeholder="Internal context, only visible to admins."
                className="w-full rounded-md border border-zinc-300 px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 mt-1"
                disabled={overrideMutation.isPending}
              />
              <div className="text-xs text-zinc-500 text-right">
                {adminNotes.length}/1000
              </div>
            </div>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={closeOverride}
              disabled={overrideMutation.isPending}
            >
              Cancel
            </Button>
            <Button
              className="bg-amber-600 hover:bg-amber-700 text-white"
              onClick={() =>
                overrideTarget && overrideMutation.mutate(overrideTarget.id)
              }
              disabled={overrideMutation.isPending}
            >
              {overrideMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : (
                <ShieldCheck className="size-4 mr-2" />
              )}
              Approve & Release Funds
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

function Stat({
  label,
  value,
  hint,
}: {
  label: string;
  value: string;
  hint?: string;
}) {
  return (
    <div className="rounded-lg border bg-muted/30 p-3">
      <div className="text-xs text-muted-foreground">{label}</div>
      <div className="text-base font-semibold tabular-nums mt-0.5">{value}</div>
      {hint ? (
        <div className="text-xs text-muted-foreground mt-0.5">{hint}</div>
      ) : null}
    </div>
  );
}

function SubmissionCard({
  submission,
  onAdminApprove,
}: {
  submission: CrSubmission;
  onAdminApprove: () => void;
}) {
  const canOverride = canAdminOverride(submission.status);
  const isRejected = /reject|declin/i.test(submission.status || '');
  return (
    <div className="rounded-lg border p-4 space-y-3">
      <div className="flex flex-wrap items-start justify-between gap-2">
        <div>
          <div className="font-medium">
            {submission.content_name || `Submission #${submission.id}`}
          </div>
          <div className="text-xs text-muted-foreground mt-0.5">
            Submitted {formatDateTime(submission.submitted_at)}
            {submission.reviewed_at
              ? ` · Reviewed ${formatDateTime(submission.reviewed_at)}`
              : ''}
          </div>
        </div>
        <span
          className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium ${statusPillClass(submission.status)}`}
        >
          {submission.status}
        </span>
      </div>

      {submission.media && submission.media.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {submission.media.map((m) => (
            <MediaPreview key={m.id} media={m} />
          ))}
        </div>
      ) : (
        <div className="text-xs text-muted-foreground">No media attached.</div>
      )}

      {submission.published_link ? (
        <div className="text-sm">
          Published:{' '}
          <a
            href={submission.published_link}
            target="_blank"
            rel="noopener noreferrer"
            className="text-primary hover:underline inline-flex items-center gap-1"
          >
            {submission.published_link}
            <ExternalLink className="size-3" />
          </a>
        </div>
      ) : null}

      {submission.review_note ? (
        <div className="rounded-md bg-amber-50 border border-amber-200 p-3 text-sm">
          <div className="text-xs text-amber-700 font-medium mb-1">
            Brand review note
          </div>
          <div className="text-amber-900 whitespace-pre-wrap">
            {submission.review_note}
          </div>
        </div>
      ) : null}

      <div className="flex justify-end gap-2 pt-1">
        {canOverride ? (
          <Button
            onClick={onAdminApprove}
            className="bg-amber-600 hover:bg-amber-700 text-white"
            size="sm"
          >
            <ShieldCheck className="size-4 mr-1" />
            {isRejected
              ? 'Override Brand Refusal & Release Funds'
              : 'Admin-Approve & Release Funds'}
          </Button>
        ) : (
          <span className="inline-flex items-center text-xs text-muted-foreground">
            <CheckCircle2 className="size-3.5 mr-1" />
            No admin action available
          </span>
        )}
      </div>
    </div>
  );
}

function MediaPreview({
  media,
}: {
  media: { url: string; media_url: string; media_type: string; mime_type: string };
}) {
  const src = resolveMediaUrl(media.media_url || media.url);
  const isVideo =
    media.media_type === 'video' || /^video\//.test(media.mime_type || '');
  const isImage =
    media.media_type === 'image' || /^image\//.test(media.mime_type || '');

  return (
    <a
      href={src}
      target="_blank"
      rel="noopener noreferrer"
      className="block rounded-md overflow-hidden border bg-zinc-50 hover:border-primary transition group"
    >
      {isVideo ? (
        // eslint-disable-next-line jsx-a11y/media-has-caption
        <video
          src={src}
          className="w-full h-40 object-cover"
          controls
          preload="metadata"
        />
      ) : isImage ? (
        // eslint-disable-next-line @next/next/no-img-element
        <img
          src={src}
          alt="Submission media"
          className="w-full h-40 object-cover"
        />
      ) : (
        <div className="h-40 flex items-center justify-center text-xs text-muted-foreground">
          {media.mime_type || 'Open file'}
        </div>
      )}
      <div className="p-2 text-xs text-muted-foreground inline-flex items-center gap-1 group-hover:text-primary">
        Open original <ExternalLink className="size-3" />
      </div>
    </a>
  );
}
