"use client";

import * as React from "react";
import { Copy, Check, Download, ExternalLink, QrCode } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";

type ShareSectionProps = {
  templateId: string;
  orgSlug: string;
  formSlug: string;
};

export function ShareSection({
  templateId,
  orgSlug,
  formSlug,
}: ShareSectionProps) {
  const [copied, setCopied] = React.useState(false);

  const baseUrl =
    typeof window !== "undefined"
      ? window.location.origin
      : "";

  const surveyUrl = `${baseUrl}/s/${orgSlug}/${formSlug}`;
  const qrEndpoint = `/api/form-templates/${templateId}/qr`;

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(surveyUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      const input = document.createElement("input");
      input.value = surveyUrl;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  const handleDownloadQR = async () => {
    try {
      const res = await fetch(qrEndpoint);
      if (!res.ok) throw new Error("Failed to download");
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `qr-${formSlug}.png`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      console.error("Failed to download QR code");
    }
  };

  return (
    <Card className="glass-card">
      <CardHeader>
        <CardTitle className="flex items-center gap-2 text-base">
          <QrCode className="size-4" />
          Share &amp; QR Code
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <label className="text-sm font-medium text-foreground">
            Public Survey URL
          </label>
          <div className="flex items-center gap-2">
            <div className="glass-input flex-1 truncate rounded-lg px-3 py-2 text-sm text-muted-foreground">
              {surveyUrl}
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={handleCopy}
              className="shrink-0"
            >
              {copied ? (
                <Check className="size-4 text-green-500" />
              ) : (
                <Copy className="size-4" />
              )}
              {copied ? "Copied" : "Copy"}
            </Button>
            <Button
              variant="outline"
              size="sm"
              render={
                <a href={surveyUrl} target="_blank" rel="noopener noreferrer" />
              }
              className="shrink-0"
            >
              <ExternalLink className="size-4" />
            </Button>
          </div>
        </div>

        <div className="space-y-2">
          <label className="text-sm font-medium text-foreground">
            QR Code
          </label>
          <div className="flex items-start gap-4">
            <div className="overflow-hidden rounded-xl border border-border bg-white p-2">
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={qrEndpoint}
                alt="Survey QR Code"
                width={160}
                height={160}
                className="size-40"
              />
            </div>
            <div className="space-y-2">
              <p className="text-sm text-muted-foreground">
                Scan this QR code to open the survey on a mobile device. Print
                it on cards, posters, or slides.
              </p>
              <Button
                variant="outline"
                size="sm"
                onClick={handleDownloadQR}
              >
                <Download className="size-4" />
                Download QR
              </Button>
            </div>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
