"use client";

import { useState, useTransition } from "react";
import Image from "next/image";
import { Copy, Check, Link2, Code, QrCode, Mail } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { Input } from "@/components/ui/Input";
import { Card } from "@/components/ui/Card";
import { Field, Label } from "@/components/ui/Card";
import { sendEmailCampaign } from "@/lib/actions/collectors";
import { cn } from "@/lib/utils/cn";

interface CollectorCenterProps {
  surveyId: string;
  surveyTitle: string;
  slug: string;
  baseUrl: string;
}

type Tab = "link" | "embed" | "qr" | "email";

export function CollectorCenter({
  surveyId,
  surveyTitle,
  slug,
  baseUrl,
}: CollectorCenterProps) {
  const [tab, setTab] = useState<Tab>("link");
  const [copied, setCopied] = useState<string | null>(null);
  const [emailSubject, setEmailSubject] = useState(
    `You're invited: ${surveyTitle}`
  );
  const [emailBody, setEmailBody] = useState(
    `Hi,\n\nWe'd love your feedback. Please take a few minutes to complete our survey.`
  );
  const [recipients, setRecipients] = useState("");
  const [emailResult, setEmailResult] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  const surveyUrl = `${baseUrl}/s/${slug}`;
  const embedCode = `<iframe src="${surveyUrl}?embed=1" width="100%" height="600" frameborder="0" style="border:1px solid #E2E8F0;border-radius:12px;"></iframe>`;
  const qrUrl = `/api/qr?url=${encodeURIComponent(surveyUrl)}`;

  function copy(text: string, key: string) {
    void navigator.clipboard.writeText(text);
    setCopied(key);
    setTimeout(() => setCopied(null), 2000);
  }

  function handleSendEmail() {
    setEmailResult(null);
    startTransition(async () => {
      const result = await sendEmailCampaign({
        surveyId,
        subject: emailSubject,
        body: emailBody,
        recipients,
      });
      if (result.success) {
        if (result.data) {
          setEmailResult(
            `Sent ${result.data.sent} email(s)${result.data.failed ? `, ${result.data.failed} failed` : ""}.`
          );
        }
      } else {
        setEmailResult(result.error ?? "Failed to send");
      }
    });
  }

  const tabs: { id: Tab; label: string; icon: typeof Link2 }[] = [
    { id: "link", label: "Web Link", icon: Link2 },
    { id: "embed", label: "Embed", icon: Code },
    { id: "qr", label: "QR Code", icon: QrCode },
    { id: "email", label: "Email", icon: Mail },
  ];

  return (
    <div className="space-y-6">
      <div className="flex gap-2 overflow-x-auto pb-1">
        {tabs.map(({ id, label, icon: Icon }) => (
          <button
            key={id}
            type="button"
            onClick={() => setTab(id)}
            className={cn(
              "flex shrink-0 items-center gap-2 rounded-full border px-4 py-2 text-[12.5px] font-semibold transition-colors",
              tab === id
                ? "border-navy bg-navy text-white"
                : "border-border bg-white text-muted hover:border-primary/40"
            )}
          >
            <Icon className="h-3.5 w-3.5" />
            {label}
          </button>
        ))}
      </div>

      <Card className="p-5 sm:p-6">
        {tab === "link" && (
          <div>
            <h3 className="mb-1 text-sm font-bold">Share your survey link</h3>
            <p className="mb-4 text-xs text-muted">
              Anyone with this link can take your survey.
            </p>
            <div className="flex flex-col gap-2 sm:flex-row">
              <Input readOnly value={surveyUrl} className="font-mono text-xs" />
              <Button
                variant="outline"
                size="sm"
                type="button"
                className="shrink-0"
                onClick={() => copy(surveyUrl, "link")}
              >
                {copied === "link" ? (
                  <Check className="mr-1 h-3.5 w-3.5" />
                ) : (
                  <Copy className="mr-1 h-3.5 w-3.5" />
                )}
                Copy
              </Button>
            </div>
            <a
              href={surveyUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="mt-3 inline-block text-xs font-semibold text-primary hover:underline"
            >
              Open survey in new tab →
            </a>
          </div>
        )}

        {tab === "embed" && (
          <div>
            <h3 className="mb-1 text-sm font-bold">Embed on your website</h3>
            <p className="mb-4 text-xs text-muted">
              Paste this snippet into your site&apos;s HTML.
            </p>
            <pre className="mb-3 overflow-x-auto rounded-lg bg-[#F8FAFC] p-3 text-[11px] leading-relaxed text-navy">
              {embedCode}
            </pre>
            <Button
              variant="outline"
              size="sm"
              type="button"
              onClick={() => copy(embedCode, "embed")}
            >
              {copied === "embed" ? (
                <Check className="mr-1 h-3.5 w-3.5" />
              ) : (
                <Copy className="mr-1 h-3.5 w-3.5" />
              )}
              Copy embed code
            </Button>
          </div>
        )}

        {tab === "qr" && (
          <div className="flex flex-col items-center sm:flex-row sm:items-start sm:gap-8">
            <div className="rounded-xl border border-border bg-white p-3 shadow-sm">
              <Image
                src={qrUrl}
                alt="Survey QR code"
                width={200}
                height={200}
                unoptimized
              />
            </div>
            <div className="mt-4 text-center sm:mt-0 sm:text-left">
              <h3 className="mb-1 text-sm font-bold">QR code</h3>
              <p className="mb-4 max-w-xs text-xs text-muted">
                Print or display this code so respondents can scan to open the
                survey on mobile.
              </p>
              <a href={qrUrl} download={`survey-${slug}.png`}>
                <Button variant="outline" size="sm" type="button">
                  Download PNG
                </Button>
              </a>
            </div>
          </div>
        )}

        {tab === "email" && (
          <div>
            <h3 className="mb-1 text-sm font-bold">Email campaign</h3>
            <p className="mb-4 text-xs text-muted">
              Paste recipient emails (one per line or comma-separated). Requires
              SMTP in your environment.
            </p>

            <Field>
              <Label>Subject</Label>
              <Input
                value={emailSubject}
                onChange={(e) => setEmailSubject(e.target.value)}
              />
            </Field>

            <Field>
              <Label>Message</Label>
              <textarea
                className="min-h-[100px] w-full rounded-sm border border-border p-3 text-sm focus:border-primary focus:outline-none"
                value={emailBody}
                onChange={(e) => setEmailBody(e.target.value)}
              />
            </Field>

            <Field>
              <Label>Recipients</Label>
              <textarea
                className="min-h-[80px] w-full rounded-sm border border-border p-3 font-mono text-xs focus:border-primary focus:outline-none"
                placeholder="alice@company.com&#10;bob@company.com"
                value={recipients}
                onChange={(e) => setRecipients(e.target.value)}
              />
            </Field>

            {emailResult && (
              <p
                className={cn(
                  "mb-3 text-sm",
                  emailResult.includes("failed") ||
                    emailResult.includes("Failed")
                    ? "text-danger"
                    : "text-success"
                )}
              >
                {emailResult}
              </p>
            )}

            <Button
              type="button"
              disabled={isPending || !recipients.trim()}
              onClick={handleSendEmail}
            >
              {isPending ? "Sending…" : "Send invitations"}
            </Button>
          </div>
        )}
      </Card>
    </div>
  );
}
