import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Copy, FileDown, Link as LinkIcon, MessageCircle } from "lucide-react";

import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { proposalsStore } from "@/lib/store/proposals-store";
import { generateProposalPdf } from "@/lib/pdf/proposal-pdf";
import type { ProposalDetail, ProposalSummary } from "@/lib/mock/types";

interface SendProposalDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  proposal: ProposalSummary | null;
}

const onlyDigits = (s: string) => s.replace(/\D+/g, "");

function buildPublicUrl(slug: string) {
  if (typeof window === "undefined") return `/p/${slug}`;
  return `${window.location.origin}/p/${slug}`;
}

function buildMessage(clientName: string, url: string) {
  return `Olá, ${clientName}! Segue sua proposta comercial da X3 Sites: ${url}`;
}

export function SendProposalDialog({
  open,
  onOpenChange,
  proposal,
}: SendProposalDialogProps) {
  const detail: ProposalDetail | undefined = proposal
    ? proposalsStore.getDetail(proposal.id)
    : undefined;

  const defaultPhone = useMemo(() => {
    const raw = detail?.whatsapp ?? "";
    return onlyDigits(raw);
  }, [detail?.whatsapp]);

  const [phone, setPhone] = useState(defaultPhone);

  useEffect(() => {
    if (open) setPhone(defaultPhone);
  }, [open, defaultPhone]);

  if (!proposal) return null;

  const publicUrl = buildPublicUrl(proposal.slug);
  const message = buildMessage(proposal.clientName, publicUrl);
  const digits = onlyDigits(phone);

  const handleCopy = async (text: string, label: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast.success(`${label} copiado`);
    } catch {
      toast.error(`Não foi possível copiar ${label.toLowerCase()}`, {
        description: text,
      });
    }
  };

  const maybeMarkAsSent = () => {
    if (proposal.status === "rascunho") {
      proposalsStore.update(proposal.id, { status: "enviada" });
      toast.success("Proposta marcada como enviada");
    }
  };

  const handleWhatsApp = () => {
    if (!digits) {
      toast.error("Informe o WhatsApp do destinatário");
      return;
    }
    const url = `https://wa.me/${digits}?text=${encodeURIComponent(message)}`;
    window.open(url, "_blank", "noopener,noreferrer");
    maybeMarkAsSent();
  };

  const handleDownloadPdf = () => {
    if (!detail) {
      toast.error("PDF indisponível para esta proposta");
      return;
    }
    try {
      generateProposalPdf(proposal, detail);
      toast.success("PDF gerado", { description: `Proposta #${proposal.number}` });
    } catch (err) {
      console.error(err);
      toast.error("Falha ao gerar PDF");
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-lg">
        <DialogHeader>
          <DialogTitle className="font-display">Enviar proposta</DialogTitle>
          <DialogDescription>
            Compartilhe a proposta com o cliente pelo WhatsApp ou copie o link público.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div className="rounded-lg border border-border/60 bg-muted/30 p-4 text-sm">
            <div className="text-xs uppercase tracking-wider text-muted-foreground">
              Cliente
            </div>
            <div className="font-medium">{proposal.clientName}</div>
            <div className="mt-2 text-xs uppercase tracking-wider text-muted-foreground">
              Proposta
            </div>
            <div className="font-medium">{proposal.title}</div>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="public-link">Link público</Label>
            <div className="flex gap-2">
              <Input id="public-link" value={publicUrl} readOnly className="font-mono text-xs" />
              <Button
                type="button"
                variant="outline"
                size="icon"
                title="Copiar link"
                onClick={() => handleCopy(publicUrl, "Link")}
              >
                <LinkIcon className="h-4 w-4" />
              </Button>
            </div>
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="wa-phone">WhatsApp do cliente</Label>
            <Input
              id="wa-phone"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              placeholder="Ex.: 5511999999999 (com DDI e DDD)"
              inputMode="tel"
            />
            {!defaultPhone && (
              <p className="text-xs text-muted-foreground">
                Cliente sem WhatsApp cadastrado — informe um número para envio.
              </p>
            )}
          </div>

          <div className="space-y-1.5">
            <Label htmlFor="wa-message">Prévia da mensagem</Label>
            <Textarea
              id="wa-message"
              value={message}
              readOnly
              rows={3}
              className="resize-none text-sm"
            />
          </div>
        </div>

        <Separator />

        <DialogFooter className="flex-col gap-2 sm:flex-row sm:justify-between">
          <div className="flex flex-wrap gap-2">
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => handleCopy(publicUrl, "Link")}
            >
              <LinkIcon className="h-4 w-4" /> Copiar link
            </Button>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={() => handleCopy(message, "Mensagem")}
            >
              <Copy className="h-4 w-4" /> Copiar mensagem
            </Button>
            <Button
              type="button"
              variant="outline"
              size="sm"
              onClick={handleDownloadPdf}
            >
              <FileDown className="h-4 w-4" /> Baixar PDF
            </Button>
          </div>
          <Button
            type="button"
            onClick={handleWhatsApp}
            className="bg-gradient-brand text-white shadow-soft"
          >
            <MessageCircle className="h-4 w-4" /> Enviar pelo WhatsApp
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
