import { useState } from "react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FolderOpen, Trash2 } from "lucide-react";
import { format } from "date-fns";

export default function LoadTemplateDialog({ templates, onLoad, onDelete, trigger }) {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState("");

  const filtered = templates.filter(t =>
    t.name.toLowerCase().includes(search.toLowerCase()) ||
    (t.associations?.name || "").toLowerCase().includes(search.toLowerCase())
  );

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        {trigger || (
          <Button variant="outline" size="sm" className="gap-1 text-xs h-8">
            <FolderOpen className="h-3 w-3" /> Load
          </Button>
        )}
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle className="text-sm">Load Saved Template</DialogTitle>
        </DialogHeader>
        <Input
          placeholder="Search templates..."
          value={search}
          onChange={e => setSearch(e.target.value)}
          className="text-sm"
        />
        <div className="max-h-[300px] overflow-auto space-y-1">
          {filtered.length === 0 && (
            <p className="text-xs text-muted-foreground text-center py-4">No saved templates found.</p>
          )}
          {filtered.map(t => (
            <div key={t.id} className="flex items-center justify-between p-2 rounded hover:bg-muted/50 group">
              <button
                className="flex-1 text-left"
                onClick={() => { onLoad(t.id); setOpen(false); }}
              >
                <p className="text-sm font-medium">{t.name}</p>
                {t.associations?.name && (
                  <p className="text-[10px] text-primary font-medium">{t.associations.name}</p>
                )}
                <p className="text-[10px] text-muted-foreground">
                  Last updated: {format(new Date(t.updated_at), "MMM d, yyyy h:mm a")}
                </p>
              </button>
              {onDelete && (
                <Button
                  variant="ghost"
                  size="sm"
                  className="h-7 w-7 p-0 opacity-0 group-hover:opacity-100"
                  onClick={(e) => { e.stopPropagation(); onDelete(t.id); }}
                >
                  <Trash2 className="h-3.5 w-3.5 text-destructive" />
                </Button>
              )}
            </div>
          ))}
        </div>
      </DialogContent>
    </Dialog>
  );
}
