import { useQuery, useMutation } from "@tanstack/react-query";
import type { SavedAiResponse } from "@shared/schema";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { 
  ArrowLeft, 
  Calendar,
  Copy,
  Trash2,
  BookOpen,
} from "lucide-react";
import { useLocation } from "wouter";
import { useState } from "react";
import { queryClient, apiRequest } from "@/lib/queryClient";

export default function SavedHistory() {
  const [, setLocation] = useLocation();
  const [expandedResponse, setExpandedResponse] = useState<string | null>(null);

  // Fetch all saved AI responses
  const { data: savedResponses = [], isLoading } = useQuery<SavedAiResponse[]>({
    queryKey: ["/api/saved-ai-responses"],
  });

  // Delete mutation
  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      return apiRequest("DELETE", `/api/saved-ai-responses/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/saved-ai-responses"] });
    },
  });

  const handleDelete = (id: string) => {
    if (confirm("Are you sure you want to delete this saved response?")) {
      deleteMutation.mutate(id);
    }
  };

  const handleCopy = (text: string) => {
    navigator.clipboard.writeText(text);
  };

  const toggleExpand = (id: string) => {
    setExpandedResponse(expandedResponse === id ? null : id);
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
          <p className="text-muted-foreground">Loading saved history...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen p-6">
      <div className="max-w-7xl mx-auto">
        <Button
          variant="ghost"
          onClick={() => setLocation("/dashboard")}
          className="mb-4"
          data-testid="button-back"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Dashboard
        </Button>

        <div className="mb-6">
          <h1 className="text-3xl font-bold mb-2 bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
            Saved AI Responses
          </h1>
          <p className="text-muted-foreground">
            View and manage your saved AI assistance history
          </p>
        </div>

        {savedResponses.length === 0 ? (
          <Card className="p-12 text-center">
            <BookOpen className="h-12 w-12 text-muted-foreground mx-auto mb-4 opacity-50" />
            <h3 className="text-lg font-semibold mb-2">No Saved Responses Yet</h3>
            <p className="text-muted-foreground mb-4">
              Save AI responses from the AI Help tab to access them here
            </p>
          </Card>
        ) : (
          <div className="space-y-4">
            {savedResponses.map((response, index) => (
              <Card 
                key={response.id} 
                className="p-6 hover-elevate transition-all"
                data-testid={`card-saved-response-${response.id}`}
              >
                <div className="flex items-start justify-between mb-4">
                  <div className="flex-1">
                    <div className="flex items-center gap-3 mb-2">
                      <h3 className="text-lg font-semibold">{response.subject}</h3>
                      <Badge variant="outline" data-testid={`badge-response-number-${response.id}`}>
                        #{savedResponses.length - index}
                      </Badge>
                    </div>
                    <p className="text-sm text-muted-foreground mb-2">
                      <strong>Step:</strong> {response.stepName}
                    </p>
                    <div className="flex items-center gap-2 text-xs text-muted-foreground">
                      <Calendar className="h-3 w-3" />
                      <span>{new Date(response.createdAt).toLocaleString()}</span>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleCopy(response.aiResponse)}
                      data-testid={`button-copy-${response.id}`}
                    >
                      <Copy className="h-4 w-4" />
                    </Button>
                    <Button
                      variant="ghost"
                      size="icon"
                      onClick={() => handleDelete(response.id)}
                      data-testid={`button-delete-${response.id}`}
                    >
                      <Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
                    </Button>
                  </div>
                </div>

                <div className="space-y-3">
                  <div className="p-3 bg-muted/30 rounded-lg">
                    <p className="text-xs font-medium text-muted-foreground mb-1">Your Question:</p>
                    <p className="text-sm">{response.userPrompt}</p>
                  </div>

                  {expandedResponse === response.id ? (
                    <div className="p-4 bg-background/50 rounded-lg border border-border/50">
                      <div className="flex items-center justify-between mb-2">
                        <p className="text-xs font-medium text-muted-foreground">AI Response:</p>
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => toggleExpand(response.id)}
                          data-testid={`button-collapse-${response.id}`}
                        >
                          Show Less
                        </Button>
                      </div>
                      <div className="text-sm whitespace-pre-wrap leading-relaxed">
                        {response.aiResponse}
                      </div>
                    </div>
                  ) : (
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => toggleExpand(response.id)}
                      className="w-full"
                      data-testid={`button-expand-${response.id}`}
                    >
                      Show Full Response
                    </Button>
                  )}
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
