"use client";

import * as React from "react";
import Link from "next/link";
import { toast } from "sonner";
import {
  ClipboardList,
  Copy,
  Check,
  Download,
  ExternalLink,
  QrCode,
  Loader2,
  Plus,
  Pencil,
  ListChecks,
} from "lucide-react";
import { Header } from "@/components/layout/header";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";

type SurveyTemplate = {
  id: string;
  name: string;
  slug: string;
  description: string | null;
  isDefault: boolean;
  isActive: boolean;
  _count?: { fields: number; cards: number };
  organization: { slug: string };
};

export default function SurveysPage() {
  const [templates, setTemplates] = React.useState<SurveyTemplate[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [copiedId, setCopiedId] = React.useState<string | null>(null);

  React.useEffect(() => {
    fetch("/api/form-templates")
      .then((r) => r.json())
      .then((data) => setTemplates(data.templates ?? []))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

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

  const getSurveyUrl = (t: SurveyTemplate) =>
    `${baseUrl}/s/${t.organization.slug}/${t.slug}`;

  const handleCopy = async (t: SurveyTemplate) => {
    const url = getSurveyUrl(t);
    try {
      await navigator.clipboard.writeText(url);
    } catch {
      const input = document.createElement("input");
      input.value = url;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
    }
    setCopiedId(t.id);
    toast.success("Survey link copied");
    setTimeout(() => setCopiedId(null), 2000);
  };

  const handleDownloadQR = async (t: SurveyTemplate) => {
    try {
      const res = await fetch(`/api/form-templates/${t.id}/qr`);
      if (!res.ok) throw new Error();
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `qr-${t.slug}.png`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      toast.error("Failed to download QR code");
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="size-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  const activeTemplates = templates.filter((t) => t.isActive);
  const inactiveTemplates = templates.filter((t) => !t.isActive);

  return (
    <div className="space-y-6">
      <Header
        title="Surveys"
        description="Share digital surveys via link or QR code"
        icon={ClipboardList}
      >
        <Button
          size="sm"
          render={<Link href="/settings/forms" />}
        >
          <Pencil className="size-4" />
          Manage Templates
        </Button>
      </Header>

      {templates.length === 0 ? (
        <div className="glass-card flex flex-col items-center gap-3 rounded-2xl p-12 text-center">
          <div className="flex size-12 items-center justify-center rounded-2xl bg-primary/10 text-primary">
            <ClipboardList className="size-6" />
          </div>
          <div>
            <p className="font-medium text-foreground">No form templates yet</p>
            <p className="mt-1 text-sm text-muted-foreground">
              Create a form template to start sharing digital surveys.
            </p>
          </div>
          <Button
            size="sm"
            className="mt-2"
            render={<Link href="/settings/forms" />}
          >
            <Plus className="size-4" />
            Create Template
          </Button>
        </div>
      ) : (
        <>
          {activeTemplates.length > 0 && (
            <div className="space-y-3">
              <h3 className="text-sm font-medium text-muted-foreground">
                Active Surveys
              </h3>
              <div className="grid gap-4 lg:grid-cols-2">
                {activeTemplates.map((t) => (
                  <SurveyCard
                    key={t.id}
                    template={t}
                    surveyUrl={getSurveyUrl(t)}
                    copied={copiedId === t.id}
                    onCopy={() => handleCopy(t)}
                    onDownloadQR={() => handleDownloadQR(t)}
                  />
                ))}
              </div>
            </div>
          )}

          {inactiveTemplates.length > 0 && (
            <div className="space-y-3">
              <h3 className="text-sm font-medium text-muted-foreground">
                Inactive
              </h3>
              <div className="grid gap-4 lg:grid-cols-2">
                {inactiveTemplates.map((t) => (
                  <SurveyCard
                    key={t.id}
                    template={t}
                    surveyUrl={getSurveyUrl(t)}
                    copied={copiedId === t.id}
                    onCopy={() => handleCopy(t)}
                    onDownloadQR={() => handleDownloadQR(t)}
                    inactive
                  />
                ))}
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function SurveyCard({
  template,
  surveyUrl,
  copied,
  onCopy,
  onDownloadQR,
  inactive,
}: {
  template: SurveyTemplate;
  surveyUrl: string;
  copied: boolean;
  onCopy: () => void;
  onDownloadQR: () => void;
  inactive?: boolean;
}) {
  return (
    <Card className={`glass-card ${inactive ? "opacity-60" : ""}`}>
      <CardHeader>
        <div className="flex items-start justify-between gap-2">
          <div className="min-w-0 flex-1">
            <CardTitle className="flex items-center gap-2 text-base">
              <span className="truncate">{template.name}</span>
              {template.isDefault && (
                <Badge variant="secondary" className="shrink-0">
                  Default
                </Badge>
              )}
              {!template.isActive && (
                <Badge variant="outline" className="shrink-0 text-muted-foreground">
                  Inactive
                </Badge>
              )}
            </CardTitle>
            {template.description && (
              <p className="mt-1 text-sm text-muted-foreground line-clamp-1">
                {template.description}
              </p>
            )}
          </div>
          <Button
            variant="outline"
            size="xs"
            render={<Link href={`/settings/forms/${template.id}`} />}
          >
            <Pencil className="size-3" />
            Edit
          </Button>
        </div>
      </CardHeader>
      <CardContent className="space-y-3">
        <div className="flex gap-3 text-xs text-muted-foreground">
          <span className="inline-flex items-center gap-1">
            <ListChecks className="size-3.5" />
            {template._count?.fields ?? 0} fields
          </span>
          <span className="inline-flex items-center gap-1">
            <ClipboardList className="size-3.5" />
            {template._count?.cards ?? 0} responses
          </span>
        </div>

        <div className="flex items-center gap-2">
          <div className="glass-input min-w-0 flex-1 truncate rounded-lg px-3 py-1.5 text-xs text-muted-foreground">
            {surveyUrl}
          </div>
          <Button variant="outline" size="xs" onClick={onCopy}>
            {copied ? (
              <Check className="size-3 text-emerald-500" />
            ) : (
              <Copy className="size-3" />
            )}
            {copied ? "Copied" : "Copy"}
          </Button>
          <Button
            variant="outline"
            size="xs"
            render={
              <a href={surveyUrl} target="_blank" rel="noopener noreferrer" />
            }
          >
            <ExternalLink className="size-3" />
          </Button>
        </div>

        <div className="flex items-center gap-2">
          <div className="overflow-hidden rounded-lg border border-border bg-white p-1">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={`/api/form-templates/${template.id}/qr`}
              alt="QR Code"
              width={80}
              height={80}
              className="size-20"
            />
          </div>
          <div className="space-y-1.5">
            <p className="text-xs text-muted-foreground">
              Scan to open the survey on a mobile device.
            </p>
            <Button variant="outline" size="xs" onClick={onDownloadQR}>
              <Download className="size-3" />
              Download QR
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
