"use client";

import * as React from "react";
import Link from "next/link";
import { toast } from "sonner";
import {
  FileText,
  Plus,
  Loader2,
  Copy,
  Trash2,
  Pencil,
  LayoutGrid,
  ListChecks,
} from "lucide-react";
import { Header } from "@/components/layout/header";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";

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

export default function FormTemplatesPage() {
  const [templates, setTemplates] = React.useState<FormTemplate[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [creating, setCreating] = React.useState(false);
  const [newName, setNewName] = React.useState("");
  const [newDescription, setNewDescription] = React.useState("");
  const [togglingId, setTogglingId] = React.useState<string | null>(null);
  const [deletingId, setDeletingId] = React.useState<string | null>(null);
  const [duplicatingId, setDuplicatingId] = React.useState<string | null>(null);

  const fetchTemplates = React.useCallback(async () => {
    try {
      const res = await fetch("/api/form-templates");
      if (!res.ok) throw new Error("Failed to fetch");
      const data = await res.json();
      setTemplates(data.templates ?? []);
      setError(null);
    } catch {
      setError("Failed to load form templates.");
    } finally {
      setLoading(false);
    }
  }, []);

  React.useEffect(() => {
    fetchTemplates();
  }, [fetchTemplates]);

  const handleCreate = async () => {
    if (!newName.trim()) return;
    setCreating(true);
    try {
      const res = await fetch("/api/form-templates", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: newName.trim(),
          description: newDescription.trim() || null,
        }),
      });
      if (!res.ok) throw new Error("Failed to create");
      toast.success("Template created");
      setNewName("");
      setNewDescription("");
      setDialogOpen(false);
      fetchTemplates();
    } catch {
      toast.error("Failed to create template");
    } finally {
      setCreating(false);
    }
  };

  const handleToggleActive = async (template: FormTemplate) => {
    setTogglingId(template.id);
    try {
      const res = await fetch(`/api/form-templates/${template.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ isActive: !template.isActive }),
      });
      if (!res.ok) throw new Error("Failed to update");
      setTemplates((prev) =>
        prev.map((t) =>
          t.id === template.id ? { ...t, isActive: !t.isActive } : t
        )
      );
      toast.success(
        `Template ${!template.isActive ? "activated" : "deactivated"}`
      );
    } catch {
      toast.error("Failed to update template");
    } finally {
      setTogglingId(null);
    }
  };

  const handleDuplicate = async (template: FormTemplate) => {
    setDuplicatingId(template.id);
    try {
      const res = await fetch(`/api/form-templates/${template.id}/duplicate`, {
        method: "POST",
      });
      if (!res.ok) throw new Error("Failed to duplicate");
      toast.success("Template duplicated");
      fetchTemplates();
    } catch {
      toast.error("Failed to duplicate template");
    } finally {
      setDuplicatingId(null);
    }
  };

  const handleDelete = async (template: FormTemplate) => {
    if (template.isDefault) {
      toast.error("Cannot delete the default template");
      return;
    }
    setDeletingId(template.id);
    try {
      const res = await fetch(`/api/form-templates/${template.id}`, {
        method: "DELETE",
      });
      if (!res.ok) throw new Error("Failed to delete");
      setTemplates((prev) => prev.filter((t) => t.id !== template.id));
      toast.success("Template deleted");
    } catch {
      toast.error("Failed to delete template");
    } finally {
      setDeletingId(null);
    }
  };

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

  if (error) {
    return (
      <div className="glass-card rounded-2xl p-8 text-center text-sm text-muted-foreground">
        {error}
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Header
        title="Form Templates"
        description="Define the fields for your connect cards and surveys"
        icon={FileText}
      >
        <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
          <DialogTrigger
            render={
              <Button size="sm">
                <Plus className="size-4" />
                Create Template
              </Button>
            }
          />
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Create Template</DialogTitle>
              <DialogDescription>
                Create a new form template with custom fields.
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4">
              <div className="space-y-2">
                <Label>Name</Label>
                <Input
                  placeholder="e.g. Sunday Service Card"
                  value={newName}
                  onChange={(e) => setNewName(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === "Enter") {
                      e.preventDefault();
                      handleCreate();
                    }
                  }}
                />
              </div>
              <div className="space-y-2">
                <Label>Description</Label>
                <Textarea
                  placeholder="Optional description..."
                  value={newDescription}
                  onChange={(e) => setNewDescription(e.target.value)}
                  rows={2}
                />
              </div>
            </div>
            <DialogFooter>
              <Button
                onClick={handleCreate}
                disabled={creating || !newName.trim()}
              >
                {creating && <Loader2 className="mr-2 size-4 animate-spin" />}
                Create
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </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">
            <FileText className="size-6" />
          </div>
          <div>
            <p className="font-medium text-foreground">No templates yet</p>
            <p className="mt-1 text-sm text-muted-foreground">
              Create your first form template to get started.
            </p>
          </div>
          <Button
            size="sm"
            className="mt-2"
            onClick={() => setDialogOpen(true)}
          >
            <Plus className="size-4" />
            Create Template
          </Button>
        </div>
      ) : (
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {templates.map((template) => (
            <Card key={template.id} className="glass-card">
              <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>
                      )}
                    </CardTitle>
                    {template.description && (
                      <p className="mt-1 line-clamp-2 text-sm text-muted-foreground">
                        {template.description}
                      </p>
                    )}
                  </div>
                  <div className="flex shrink-0 items-center gap-1.5">
                    <Switch
                      size="sm"
                      checked={template.isActive}
                      onCheckedChange={() => handleToggleActive(template)}
                      disabled={togglingId === template.id}
                    />
                  </div>
                </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">
                    <LayoutGrid className="size-3.5" />
                    {template._count?.cards ?? 0} cards
                  </span>
                </div>
                <div className="flex items-center gap-1.5">
                  <Button
                    variant="outline"
                    size="xs"
                    render={<Link href={`/settings/forms/${template.id}`} />}
                  >
                    <Pencil className="size-3" />
                    Edit
                  </Button>
                  <Button
                    variant="outline"
                    size="xs"
                    onClick={() => handleDuplicate(template)}
                    disabled={duplicatingId === template.id}
                  >
                    {duplicatingId === template.id ? (
                      <Loader2 className="size-3 animate-spin" />
                    ) : (
                      <Copy className="size-3" />
                    )}
                    Duplicate
                  </Button>
                  <Button
                    variant="destructive"
                    size="xs"
                    onClick={() => handleDelete(template)}
                    disabled={
                      template.isDefault || deletingId === template.id
                    }
                  >
                    {deletingId === template.id ? (
                      <Loader2 className="size-3 animate-spin" />
                    ) : (
                      <Trash2 className="size-3" />
                    )}
                    Delete
                  </Button>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
