"use client";

import { useCallback, useEffect, useState } from "react";
import { toast } from "sonner";
import { Loader2 as Loader, Zap, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardBody, CardHeader, CardTitle } from "@/components/ui/card";
import { Input, Textarea, Label } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";

type QuickReply = { id: string; title: string; shortcut: string; body: string };

export default function QuickRepliesPage() {
  const [items, setItems] = useState<QuickReply[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    const res = await fetch("/api/quick-replies");
    const j = await res.json().catch(() => ({}));
    if (res.ok) setItems(j.items ?? []);
    else toast.error(j.error ?? "Failed to load quick replies.");
    setLoading(false);
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function create(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSaving(true);
    const data: Record<string, string> = {};
    for (const [k, v] of new FormData(e.currentTarget).entries()) data[k] = String(v);
    const res = await fetch("/api/quick-replies", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    const j = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) return toast.error(j.error ?? "Create failed.");
    toast.success("Quick reply created.");
    e.currentTarget.reset();
    load();
  }

  async function remove(id: string) {
    const res = await fetch("/api/quick-replies", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ id }),
    });
    if (!res.ok) return toast.error("Delete failed.");
    toast.success("Deleted.");
    load();
  }

  return (
    <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
      <Card>
        <CardHeader>
          <CardTitle>New quick reply</CardTitle>
        </CardHeader>
        <CardBody>
          <form onSubmit={create} className="space-y-4">
            <div>
              <Label>Title</Label>
              <Input name="title" placeholder="e.g. Shipping info" required />
            </div>
            <div>
              <Label>Shortcut</Label>
              <Input name="shortcut" placeholder="/shipping" defaultValue="/" required />
            </div>
            <div>
              <Label>Message body</Label>
              <Textarea name="body" rows={3} placeholder="Your order ships within 1-2 business days." required />
            </div>
            <div className="flex justify-end">
              <Button type="submit" loading={saving}>
                <Zap className="h-4 w-4" /> Create
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">
              Type the shortcut in the composer to autofill the message.
            </p>
          </form>
        </CardBody>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>Saved replies</CardTitle>
        </CardHeader>
        <CardBody>
          {loading ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader className="h-4 w-4 animate-spin" /> Loading…
            </div>
          ) : items.length === 0 ? (
            <p className="text-sm text-muted-foreground">No quick replies yet.</p>
          ) : (
            <div className="space-y-2">
              {items.map((q) => (
                <div key={q.id} className="rounded-lg border border-border px-4 py-3">
                  <div className="flex items-center gap-2">
                    <Badge tone="indigo">{q.shortcut}</Badge>
                    <span className="text-sm font-semibold text-foreground">{q.title}</span>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="ml-auto h-7 w-7 text-muted-foreground hover:text-red-600"
                      onClick={() => remove(q.id)}
                    >
                      <Trash2 className="h-3.5 w-3.5" />
                    </Button>
                  </div>
                  <p className="mt-1.5 whitespace-pre-wrap text-sm text-muted-foreground">{q.body}</p>
                </div>
              ))}
            </div>
          )}
        </CardBody>
      </Card>
    </div>
  );
}
