'use client';

import { useEffect, useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { format } from 'date-fns';
import { CheckCircle2, MessageCircle, Send } from 'lucide-react';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
  SheetDescription,
} from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Spinner } from '@/components/ui/spinners';
import {
  approveInfluencerRegistration,
  rejectInfluencerRegistration,
  sendInfluencerCredentials,
} from '@/network/apis/dashboard/marketplace/influencer-registrations.apis';
import type { InfluencerRegistrationRow } from '@/network/apis/dashboard/marketplace/influencer-registrations.types';
import { statusPillClass } from './utils';

const safeFormat = (value: string | null | undefined) => {
  if (!value) return '—';
  try {
    return format(new Date(value), 'PP p');
  } catch {
    return value;
  }
};

export function InfluencerRegistrationDetailSheet({
  registration,
  open,
  onClose,
  waConnected,
}: {
  registration: InfluencerRegistrationRow | null;
  open: boolean;
  onClose: () => void;
  waConnected: boolean;
}) {
  const queryClient = useQueryClient();
  const [confirmKind, setConfirmKind] = useState<'approve' | 'reject' | null>(null);
  const [rejectionReason, setRejectionReason] = useState('');

  useEffect(() => {
    setRejectionReason('');
    setConfirmKind(null);
  }, [registration?.id]);

  const invalidate = () =>
    queryClient.invalidateQueries({ queryKey: ['admin-influencer-registrations'] });

  const handleError = (error: unknown, fallback: string) => {
    const msg =
      (error as { response?: { data?: { message?: string } } })?.response?.data
        ?.message || fallback;
    toast.error(msg);
  };

  const approveMutation = useMutation({
    mutationFn: (id: number) => approveInfluencerRegistration(id),
    onSuccess: (row) => {
      toast.success(
        row?.credentials_sent
          ? 'Approved — credentials sent over WhatsApp.'
          : 'Approved, but the WhatsApp message failed. Connect the notification phone and re-send.',
      );
      invalidate();
      setConfirmKind(null);
      onClose();
    },
    onError: (e) => handleError(e, 'Failed to approve'),
  });

  const rejectMutation = useMutation({
    mutationFn: (id: number) => rejectInfluencerRegistration(id, rejectionReason.trim()),
    onSuccess: () => {
      toast.success('Request rejected');
      invalidate();
      setConfirmKind(null);
      onClose();
    },
    onError: (e) => handleError(e, 'Failed to reject'),
  });

  const resendMutation = useMutation({
    mutationFn: (id: number) => sendInfluencerCredentials(id),
    onSuccess: () => {
      toast.success('Credentials sent over WhatsApp');
      invalidate();
    },
    onError: (e) => handleError(e, 'Failed to send credentials'),
  });

  if (!registration) return null;

  const isPending = registration.status === 'pending';
  const isApproved = registration.status === 'approved';
  const submitting = approveMutation.isPending || rejectMutation.isPending;
  const whatsapp = `${registration.phone_country_code} ${registration.phone_number}`;

  return (
    <>
      <Sheet open={open} onOpenChange={(o) => !o && onClose()}>
        <SheetContent side="right" className="w-full sm:max-w-xl overflow-y-auto">
          <SheetHeader>
            <SheetTitle className="flex items-center gap-3">
              {registration.name}
              <span
                className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium capitalize ${statusPillClass(registration.status)}`}
              >
                {registration.status}
              </span>
            </SheetTitle>
            <SheetDescription>
              Request #{registration.id} · submitted {safeFormat(registration.created_at)}
            </SheetDescription>
          </SheetHeader>

          <div className="space-y-6 px-4 pb-6">
            {/* Contact */}
            <div className="space-y-2">
              <h3 className="text-sm font-semibold">Influencer details</h3>
              <div className="rounded-lg border p-3 space-y-2 text-sm">
                <Row label="Name" value={registration.name} />
                <Row label="Email" value={registration.email} />
                <Row label="WhatsApp" value={whatsapp} mono />
                {registration.social_platform || registration.social_handle ? (
                  <Row
                    label="Social"
                    value={`${registration.social_platform ?? ''}${
                      registration.social_handle ? ` — ${registration.social_handle}` : ''
                    }`}
                  />
                ) : null}
              </div>
            </div>

            {/* Outcome / linked account */}
            {isApproved ? (
              <div className="space-y-2">
                <h3 className="text-sm font-semibold">Account</h3>
                <div className="rounded-lg border p-3 text-sm space-y-1">
                  <Row
                    label="Linked user"
                    value={
                      registration.linkedUser
                        ? `${registration.linkedUser.name} (#${registration.linkedUser.id})`
                        : registration.linked_user_id
                          ? `#${registration.linked_user_id}`
                          : '—'
                    }
                  />
                  <Row label="Approved" value={safeFormat(registration.approved_at)} />
                  <div className="flex items-center gap-2">
                    {registration.credentials_sent ? (
                      <span className="inline-flex items-center gap-1 text-green-700">
                        <CheckCircle2 className="size-4" /> Credentials sent on{' '}
                        {safeFormat(registration.credentials_sent_at)}
                      </span>
                    ) : (
                      <span className="text-amber-700">Credentials not sent yet.</span>
                    )}
                  </div>
                </div>
              </div>
            ) : null}

            {registration.rejection_reason ? (
              <div className="space-y-2">
                <h3 className="text-sm font-semibold text-red-600">Rejection reason</h3>
                <div className="rounded-lg border border-red-200 bg-red-50 p-3 text-sm whitespace-pre-wrap">
                  {registration.rejection_reason}
                </div>
              </div>
            ) : null}

            {/* WhatsApp connection warning */}
            {(isPending || (isApproved && !registration.credentials_sent)) && !waConnected ? (
              <div className="flex items-start gap-2 rounded-lg border border-amber-300 bg-amber-50 p-3 text-sm text-amber-800">
                <MessageCircle className="size-4 mt-0.5 shrink-0" />
                <span>
                  The Sanad notification WhatsApp is not connected. Connect it from the card
                  above before approving, otherwise the credentials message will fail (you can
                  re-send afterwards).
                </span>
              </div>
            ) : null}

            {/* Actions */}
            <div className="flex flex-wrap gap-2 pt-2 border-t">
              {isPending ? (
                <>
                  <Button onClick={() => setConfirmKind('approve')} disabled={submitting}>
                    Approve &amp; send credentials
                  </Button>
                  <Button
                    variant="outline"
                    onClick={() => setConfirmKind('reject')}
                    disabled={submitting}
                    className="text-red-600 border-red-200 hover:bg-red-50"
                  >
                    Reject
                  </Button>
                </>
              ) : null}
              {isApproved ? (
                <Button
                  variant="outline"
                  onClick={() => resendMutation.mutate(registration.id)}
                  disabled={resendMutation.isPending}
                >
                  {resendMutation.isPending ? (
                    <Spinner className="size-4 animate-spin mr-2" />
                  ) : (
                    <Send className="size-4 mr-2" />
                  )}
                  Re-send credentials
                </Button>
              ) : null}
            </div>
          </div>
        </SheetContent>
      </Sheet>

      {/* Approve confirm */}
      <Dialog open={confirmKind === 'approve'} onOpenChange={(o) => !o && setConfirmKind(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Approve {registration.name}?</DialogTitle>
            <DialogDescription>
              This creates an influencer account and sends the login details to{' '}
              <span className="font-mono">{whatsapp}</span> over WhatsApp.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmKind(null)}>
              Cancel
            </Button>
            <Button
              onClick={() => approveMutation.mutate(registration.id)}
              disabled={approveMutation.isPending}
            >
              {approveMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : null}
              Confirm approve
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Reject confirm */}
      <Dialog open={confirmKind === 'reject'} onOpenChange={(o) => !o && setConfirmKind(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reject {registration.name}?</DialogTitle>
            <DialogDescription>
              The request will be marked as rejected. No account is created.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-3">
            <div>
              <Label>Rejection reason (optional)</Label>
              <Textarea
                value={rejectionReason}
                onChange={(e) => setRejectionReason(e.target.value)}
                placeholder="Internal note about why this request was rejected."
                rows={4}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setConfirmKind(null)}>
              Cancel
            </Button>
            <Button
              variant="outline"
              className="text-red-600 border-red-300 hover:bg-red-50"
              onClick={() => rejectMutation.mutate(registration.id)}
              disabled={rejectMutation.isPending}
            >
              {rejectMutation.isPending ? (
                <Spinner className="size-4 animate-spin mr-2" />
              ) : null}
              Confirm reject
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
  return (
    <div className="flex items-start justify-between gap-3">
      <span className="text-xs text-muted-foreground">{label}</span>
      <span className={`font-medium text-right ${mono ? 'font-mono' : ''}`}>{value}</span>
    </div>
  );
}
