"use client";

import React, { useState } from "react";
import { Monitor, Smartphone, Code, Eye, Copy } from "lucide-react";
import { toast } from "sonner";

import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/shared/components/ui/card";
import { Button } from "@/shared/components/ui/button";

interface CampaignPreviewCardProps {
  htmlBody: string;
  title: string;
  subject: string;
  senderName?: string;
  senderEmail?: string;
}

export function CampaignPreviewCard({
  htmlBody,
  title,
  subject,
  senderName,
  senderEmail,
}: CampaignPreviewCardProps) {
  const [device, setDevice] = useState<"desktop" | "mobile">("desktop");
  const [viewMode, setViewMode] = useState<"visual" | "code">("visual");

  const safeHtml = htmlBody.includes("<head>")
    ? htmlBody.replace("<head>", '<head><base target="_blank">')
    : `<base target="_blank">${htmlBody}`;

  return (
    <Card className="bg-white border border-zinc-200/80 text-zinc-900 shadow-xs rounded-2xl overflow-hidden">
      <CardHeader className="border-b border-zinc-100 p-5 sm:p-6 pb-4">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
          <div>
            <CardTitle className="text-base font-bold text-zinc-900 flex items-center gap-2">
              <Eye className="w-5 h-5 text-[#0F9FDF]" />
              <span>Conteúdo &amp; Arte da Newsletter (Rascunho)</span>
            </CardTitle>
            <CardDescription className="text-xs text-zinc-500 mt-1">
              Visualização exata do e-mail que será enviado para os contatos da lista
            </CardDescription>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            <div className="flex items-center bg-zinc-100 border border-zinc-200 rounded-xl p-1">
              <Button
                variant="ghost"
                size="sm"
                className={`h-8 px-3 text-xs font-semibold rounded-lg transition-all ${
                  device === "desktop" ? "bg-[#0F9FDF] text-white shadow-2xs" : "text-zinc-600 hover:text-zinc-900"
                }`}
                onClick={() => setDevice("desktop")}
              >
                <Monitor className="w-3.5 h-3.5 mr-1" />
                Desktop
              </Button>
              <Button
                variant="ghost"
                size="sm"
                className={`h-8 px-3 text-xs font-semibold rounded-lg transition-all ${
                  device === "mobile" ? "bg-[#0F9FDF] text-white shadow-2xs" : "text-zinc-600 hover:text-zinc-900"
                }`}
                onClick={() => setDevice("mobile")}
              >
                <Smartphone className="w-3.5 h-3.5 mr-1" />
                Mobile
              </Button>
            </div>

            <Button
              variant="outline"
              size="sm"
              onClick={() => setViewMode(viewMode === "visual" ? "code" : "visual")}
              className="border-zinc-300 bg-white text-zinc-700 hover:bg-zinc-100 text-xs h-9 rounded-xl font-semibold"
            >
              <Code className="w-3.5 h-3.5 mr-1 text-emerald-600" />
              {viewMode === "visual" ? "Ver HTML" : "Ver Visual"}
            </Button>
          </div>
        </div>
      </CardHeader>

      <CardContent className="p-4 sm:p-6 bg-zinc-50/50 flex flex-col items-center overflow-x-auto">
        {viewMode === "visual" ? (
          <div
            className={`transition-all duration-300 bg-white rounded-2xl shadow-xs overflow-hidden border border-zinc-200/80 ${
              device === "desktop" ? "w-full max-w-[640px]" : "w-[360px] max-w-full"
            } min-h-[500px] p-4 sm:p-6 text-zinc-900`}
          >
            {/* Header info in email preview */}
            <div className="border-b border-zinc-100 pb-3 mb-4 flex flex-col sm:flex-row sm:items-center justify-between gap-1 text-xs">
              <div className="min-w-0 flex-1">
                <span className="font-bold text-zinc-900 block text-sm break-words">{title}</span>
                <span className="text-zinc-500 text-xs break-words">Assunto: {subject}</span>
              </div>
              {senderEmail && (
                <span className="text-[11px] text-zinc-500 font-mono shrink-0 mt-1 sm:mt-0">
                  De: {senderName ? `${senderName} <${senderEmail}>` : senderEmail}
                </span>
              )}
            </div>

            {/* Iframe with safe height and scroll */}
            <iframe
              srcDoc={safeHtml}
              title="Preview da Newsletter"
              className="w-full min-h-[440px] border-0 rounded-xl shadow-inner bg-white overflow-auto"
              sandbox="allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts"
            />
          </div>
        ) : (
          <div className="w-full max-w-4xl space-y-2">
            <div className="flex justify-end">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => {
                  navigator.clipboard.writeText(htmlBody);
                  toast.success("Código HTML copiado!");
                }}
                className="text-xs text-[#0F9FDF] hover:text-[#0C87BD] font-semibold"
              >
                <Copy className="w-3.5 h-3.5 mr-1" />
                Copiar Código HTML
              </Button>
            </div>
            <textarea
              readOnly
              value={htmlBody}
              className="w-full min-h-[400px] bg-zinc-900 border border-zinc-800 rounded-2xl p-4 font-mono text-xs text-emerald-400 resize-none focus:outline-none"
            />
          </div>
        )}
      </CardContent>
    </Card>
  );
}
