'use client';

import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { ClipboardCopy, Link as LinkIcon, Loader2 } from 'lucide-react';
import { toast } from 'sonner';

import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';

interface CreateResponse {
  data: { id: string; slug: string; targetUrl: string; url: string };
}

interface Props {
  /** Optional FK to attribute clicks back to a specific document_sends
   *  row. When supplied, every click on the minted link increments the
   *  send's click counter so the per-email open + click stats reconcile. */
  sendId?: string;
  /** Called with the minted public URL so the parent compose surface can
   *  paste it into the email body / textarea. */
  onInsert?: (url: string) => void;
  /** Display variant - `inline` is a small text button suitable for a
   *  toolbar; `default` is a sized button suitable for a form footer. */
  variant?: 'inline' | 'default';
}

/**
 * Compose-surface affordance for minting a trackable redirect link.
 * Opens a small dialog: rep pastes the destination URL, clicks Create,
 * gets the public `/q/<slug>` URL with a Copy button + an "Insert into
 * message" action that calls back to the parent.
 *
 * Permission-gated on `email.send` so reps without send rights don't
 * see the affordance - same as the server-side check on the POST route.
 */
export function TrackedLinkComposerButton({ sendId, onInsert, variant = 'inline' }: Props) {
  const [open, setOpen] = useState(false);
  const [target, setTarget] = useState('');
  const [result, setResult] = useState<CreateResponse['data'] | null>(null);

  const create = useMutation({
    mutationFn: async () => {
      const res = await apiFetch<CreateResponse>('/api/v1/tracked-links', {
        method: 'POST',
        body: { targetUrl: target.trim(), sendId },
      });
      return res.data;
    },
    onSuccess: (data) => {
      setResult(data);
    },
    onError: (err) => toastError(err),
  });

  function reset() {
    setTarget('');
    setResult(null);
  }

  return (
    <>
      <Button
        type="button"
        size={variant === 'default' ? 'sm' : 'sm'}
        variant={variant === 'default' ? 'default' : 'outline'}
        onClick={() => {
          reset();
          setOpen(true);
        }}
        className={variant === 'inline' ? 'h-7 px-2 text-xs' : undefined}
        title="Mint a tracked link the recipient can click - clicks count back to this send."
      >
        <LinkIcon
          className={variant === 'inline' ? 'mr-1 size-3' : 'mr-1.5 size-3.5'}
          aria-hidden
        />
        Tracked link
      </Button>

      <Dialog
        open={open}
        onOpenChange={(o) => {
          setOpen(o);
          if (!o) reset();
        }}
      >
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Mint a tracked link</DialogTitle>
            <DialogDescription>
              The recipient clicks the public &lt;APP_URL&gt;/q/&lt;slug&gt; URL and lands on the
              destination URL. Each click is counted + attributed to{' '}
              {sendId ? 'this send' : 'your account'} in the analytics surface.
            </DialogDescription>
          </DialogHeader>
          {result ? (
            <div className="space-y-2 py-2">
              <Label htmlFor="tracked-link-url" className="text-xs uppercase tracking-wide">
                Tracked URL
              </Label>
              <div className="flex items-center gap-2">
                <Input
                  id="tracked-link-url"
                  value={result.url}
                  readOnly
                  className="font-mono text-xs"
                />
                <Button
                  type="button"
                  size="sm"
                  variant="outline"
                  onClick={() => {
                    void navigator.clipboard.writeText(result.url);
                    toast.success('Link copied');
                  }}
                >
                  <ClipboardCopy className="mr-1.5 size-3.5" aria-hidden />
                  Copy
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                Redirects to{' '}
                <a
                  href={result.targetUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="underline-offset-2 hover:underline"
                >
                  {result.targetUrl}
                </a>
                .
              </p>
            </div>
          ) : (
            <div className="space-y-2 py-2">
              <Label htmlFor="tracked-link-target">Destination URL</Label>
              <Input
                id="tracked-link-target"
                type="url"
                value={target}
                onChange={(e) => setTarget(e.target.value)}
                placeholder="https://portnimara.com/yachts/sapphire"
              />
            </div>
          )}
          <DialogFooter>
            {result ? (
              <>
                <Button variant="outline" onClick={() => setOpen(false)}>
                  Close
                </Button>
                {onInsert ? (
                  <Button
                    onClick={() => {
                      onInsert(result.url);
                      toast.success('Inserted');
                      setOpen(false);
                    }}
                  >
                    Insert into message
                  </Button>
                ) : null}
              </>
            ) : (
              <>
                <Button variant="outline" onClick={() => setOpen(false)}>
                  Cancel
                </Button>
                <Button
                  onClick={() => create.mutate()}
                  disabled={create.isPending || !target.trim()}
                >
                  {create.isPending ? (
                    <Loader2 className="mr-1.5 size-3.5 animate-spin" aria-hidden />
                  ) : (
                    <LinkIcon className="mr-1.5 size-3.5" aria-hidden />
                  )}
                  Create
                </Button>
              </>
            )}
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
