import { useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Input } from "@/components/ui/input";
import { Sparkles, Search, Loader2, X } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { analyticsService } from "@/services/analytics.service";
import { useToast } from "@/hooks/use-toast";

export default function AiSearchBar() {
  const [query, setQuery] = useState("");
  const navigate = useNavigate();
  const { toast } = useToast();

  const searchMutation = useMutation({
    mutationFn: (q: string) => analyticsService.search(q),
    onError: (err: Error) => {
      toast({
        variant: "destructive",
        title: "Search failed",
        description: err.message || "Could not complete AI search.",
      });
    },
  });

  const handleSearch = () => {
    if (!query.trim() || searchMutation.isPending) return;
    searchMutation.mutate(query.trim());
  };

  const result = searchMutation.data;

  return (
    <div className="relative max-w-md w-full">
      <div className="relative">
        <Sparkles className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-primary" />
        <Search className="absolute left-7 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
        <Input
          placeholder="Ask anything... e.g. 'Show students with low attendance'"
          className="pl-12 pr-8 h-9 text-sm bg-muted/50 border-0 focus-visible:ring-1"
          value={query}
          onChange={(e) => {
            setQuery(e.target.value);
            searchMutation.reset();
          }}
          onKeyDown={(e) => e.key === "Enter" && handleSearch()}
        />
        {query && (
          <button
            onClick={() => {
              setQuery("");
              searchMutation.reset();
            }}
            className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
          >
            <X className="h-3.5 w-3.5" />
          </button>
        )}
      </div>

      {(searchMutation.isPending || result !== undefined) && (
        <div className="absolute top-full mt-1 left-0 right-0 z-50 rounded-lg border bg-popover p-3 shadow-md">
          {searchMutation.isPending ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground">
              <Loader2 className="h-4 w-4 animate-spin text-primary" />
              AI is searching...
            </div>
          ) : result?.answer ? (
            <div className="text-sm space-y-2 max-h-64 overflow-y-auto">
              <div className="flex items-start gap-2 pb-2">
                <Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
                <p className="text-muted-foreground">{result.answer}</p>
              </div>
              {result.suggestions?.length > 0 && (
                <div className="border-t pt-2 space-y-1">
                  <p className="text-xs font-semibold text-primary">Related queries</p>
                  {result.suggestions.map((s, i) => (
                    <button
                      key={i}
                      type="button"
                      className="block text-xs text-primary hover:underline"
                      onClick={() => { setQuery(s); searchMutation.mutate(s); }}
                    >
                      {s}
                    </button>
                  ))}
                </div>
              )}
              {result.related_actions?.map((a, i) => (
                <button
                  key={i}
                  type="button"
                  className="text-xs text-primary hover:underline"
                  onClick={() => navigate(a.action)}
                >
                  {a.label}
                </button>
              ))}
            </div>
          ) : (
            <div className="text-sm flex items-start gap-2">
              <Sparkles className="h-4 w-4 text-primary shrink-0 mt-0.5" />
              <p>
                No results for &quot;{query}&quot;. Try a different question or keyword.
              </p>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
