import { useState, useRef, useEffect } from "react";
import { useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Sparkles, Send, Loader2, Lightbulb, CheckCircle } from "lucide-react";
import { useAuth } from "@/hooks/use-auth";
import { useToast } from "@/hooks/use-toast";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useLocation } from "wouter";

interface Message {
  id: string;
  role: "user" | "assistant";
  content: string;
  timestamp: Date;
  showPlanAction?: boolean;
}

export default function AIAssistant() {
  const { user } = useAuth();
  const { toast } = useToast();
  const [, setLocation] = useLocation();
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "welcome",
      role: "assistant",
      content: "Hello! I'm your AI planning assistant. I can help you create plans, break down goals into steps, suggest improvements, and answer questions about your planning strategy. How can I help you today?",
      timestamp: new Date(),
    },
  ]);
  const [input, setInput] = useState("");
  const [showPlanDialog, setShowPlanDialog] = useState(false);
  const [planName, setPlanName] = useState("");
  const [planDescription, setPlanDescription] = useState("");
  const [planSteps, setPlanSteps] = useState<string[]>([""]);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const createPlanMutation = useMutation({
    mutationFn: async (planData: { planName: string; planDescription: string; steps: string[] }) => {
      const planRes = await apiRequest("POST", "/api/plans", {
        planName: planData.planName,
        planDescription: planData.planDescription,
      });
      const plan = await planRes.json();
      
      // Create steps for the plan
      const validSteps = planData.steps.filter(s => s.trim());
      for (const stepText of validSteps) {
        await apiRequest("POST", "/api/steps", {
          planId: plan.id,
          stepText,
          status: "pending",
        });
      }
      
      return { plan, stepCount: validSteps.length };
    },
    onSuccess: ({ plan, stepCount }) => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans"] });
      toast({
        title: "Plan created successfully!",
        description: `${plan.planName} has been added to your plans.`,
      });
      setShowPlanDialog(false);
      setPlanName("");
      setPlanDescription("");
      setPlanSteps([""]);
      
      const successMessage: Message = {
        id: Date.now().toString(),
        role: "assistant",
        content: `Great! I've created your plan "${plan.planName}"${stepCount > 0 ? ` with ${stepCount} step${stepCount > 1 ? 's' : ''}` : ''}. You can view and manage it from your dashboard.`,
        timestamp: new Date(),
      };
      setMessages((prev) => [...prev, successMessage]);
      
      setTimeout(() => setLocation(`/plan/${plan.id}`), 1500);
    },
  });

  const aiMutation = useMutation({
    mutationFn: async (prompt: string) => {
      const isPlanRequest = /create|make|build|start|help.*plan/i.test(prompt);
      const modifiedPrompt = isPlanRequest 
        ? `${prompt}\n\nPlease provide a brief 2-3 sentence response about creating this type of plan. Keep it short and actionable.`
        : prompt;
      
      const res = await apiRequest("POST", "/api/ai/suggest", { prompt: modifiedPrompt });
      return { ...await res.json(), isPlanRequest };
    },
    onSuccess: (data, prompt) => {
      const newMessage: Message = {
        id: Date.now().toString(),
        role: "assistant",
        content: data.suggestion,
        timestamp: new Date(),
        showPlanAction: data.isPlanRequest,
      };
      setMessages((prev) => [...prev, newMessage]);
    },
  });

  const handleSend = () => {
    if (!input.trim() || aiMutation.isPending) return;

    const userMessage: Message = {
      id: Date.now().toString(),
      role: "user",
      content: input,
      timestamp: new Date(),
    };

    setMessages((prev) => [...prev, userMessage]);
    aiMutation.mutate(input);
    setInput("");
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  const handleCreatePlan = () => {
    setShowPlanDialog(true);
  };

  const handleSubmitPlan = () => {
    if (!planName.trim()) {
      toast({
        title: "Plan name required",
        description: "Please enter a name for your plan.",
        variant: "destructive",
      });
      return;
    }

    createPlanMutation.mutate({
      planName,
      planDescription,
      steps: planSteps,
    });
  };

  const addStep = () => {
    setPlanSteps([...planSteps, ""]);
  };

  const updateStep = (index: number, value: string) => {
    const updated = [...planSteps];
    updated[index] = value;
    setPlanSteps(updated);
  };

  const removeStep = (index: number) => {
    setPlanSteps(planSteps.filter((_, i) => i !== index));
  };

  const suggestedPrompts = [
    "Help me create a business plan for a startup",
    "Break down my fitness goals into weekly steps",
    "Suggest ways to improve my productivity",
    "How do I prioritize multiple projects?",
  ];

  const handleSuggestedPrompt = (prompt: string) => {
    setInput(prompt);
  };

  return (
    <div className="flex flex-col h-full">
      {/* Header */}
      <div className="border-b p-6 bg-gradient-to-r from-indigo-500/10 to-purple-600/10 backdrop-blur-sm">
        <div className="max-w-5xl mx-auto">
          <div className="flex items-center gap-3">
            <div className="p-3 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600">
              <Sparkles className="h-6 w-6 text-white" />
            </div>
            <div>
              <h1 className="text-2xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
                AI Assistant
              </h1>
              <p className="text-sm text-muted-foreground">
                Your intelligent planning companion
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Messages Container */}
      <div className="flex-1 overflow-auto p-6">
        <div className="max-w-5xl mx-auto space-y-4">
          {messages.map((message) => (
            <div
              key={message.id}
              className={`flex gap-3 ${
                message.role === "user" ? "justify-end" : "justify-start"
              }`}
              data-testid={`message-${message.id}`}
            >
              {message.role === "assistant" && (
                <Avatar className="h-8 w-8 flex-shrink-0">
                  <AvatarFallback className="bg-gradient-to-br from-indigo-500 to-purple-600 text-white">
                    <Sparkles className="h-4 w-4" />
                  </AvatarFallback>
                </Avatar>
              )}

              <Card
                className={`p-4 max-w-[80%] ${
                  message.role === "user"
                    ? "bg-gradient-to-br from-indigo-500 to-purple-600 text-white"
                    : "bg-card"
                }`}
              >
                <p className="text-sm whitespace-pre-wrap">{message.content}</p>
                
                {message.showPlanAction && message.role === "assistant" && (
                  <div className="mt-4 pt-4 border-t">
                    <p className="text-sm font-medium mb-3">Would you like me to help you create this plan?</p>
                    <Button
                      onClick={handleCreatePlan}
                      className="bg-gradient-to-r from-indigo-500 to-purple-600"
                      size="sm"
                      data-testid="button-create-plan-from-chat"
                    >
                      <CheckCircle className="h-4 w-4 mr-2" />
                      Yes, Create Plan
                    </Button>
                  </div>
                )}
                
                <p
                  className={`text-xs mt-2 ${
                    message.role === "user"
                      ? "text-indigo-100"
                      : "text-muted-foreground"
                  }`}
                >
                  {message.timestamp.toLocaleTimeString()}
                </p>
              </Card>

              {message.role === "user" && (
                <Avatar className="h-8 w-8 flex-shrink-0">
                  <AvatarFallback>
                    {user?.firstName?.[0]}
                    {user?.lastName?.[0]}
                  </AvatarFallback>
                </Avatar>
              )}
            </div>
          ))}

          {aiMutation.isPending && (
            <div className="flex gap-3" data-testid="status-ai-thinking">
              <Avatar className="h-8 w-8 flex-shrink-0">
                <AvatarFallback className="bg-gradient-to-br from-indigo-500 to-purple-600 text-white">
                  <Sparkles className="h-4 w-4" />
                </AvatarFallback>
              </Avatar>
              <Card className="p-4">
                <div className="flex items-center gap-2">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  <span className="text-sm text-muted-foreground">
                    AI is thinking...
                  </span>
                </div>
              </Card>
            </div>
          )}

          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* Suggested Prompts (shown when no user messages) */}
      {messages.filter((m) => m.role === "user").length === 0 && (
        <div className="border-t p-4 bg-muted/30">
          <div className="max-w-5xl mx-auto">
            <div className="flex items-center gap-2 mb-3">
              <Lightbulb className="h-4 w-4 text-indigo-500" />
              <p className="text-sm font-medium">Suggested prompts:</p>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
              {suggestedPrompts.map((prompt, index) => (
                <Button
                  key={index}
                  variant="outline"
                  className="justify-start text-left"
                  onClick={() => handleSuggestedPrompt(prompt)}
                  data-testid={`button-suggested-prompt-${index}`}
                >
                  <span className="text-sm truncate">{prompt}</span>
                </Button>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Input Area */}
      <div className="border-t p-4 bg-background">
        <div className="max-w-5xl mx-auto">
          <div className="flex gap-2">
            <Textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="Ask me anything about planning, goals, or productivity..."
              className="min-h-[60px] max-h-[200px] resize-none"
              disabled={aiMutation.isPending}
              data-testid="textarea-chat-input"
            />
            <Button
              onClick={handleSend}
              disabled={!input.trim() || aiMutation.isPending}
              className="bg-gradient-to-r from-indigo-500 to-purple-600 self-end"
              size="icon"
              data-testid="button-send-message"
            >
              {aiMutation.isPending ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </Button>
          </div>
          <p className="text-xs text-muted-foreground mt-2">
            Press Enter to send, Shift+Enter for new line
          </p>
        </div>
      </div>

      {/* Plan Creation Dialog */}
      <Dialog open={showPlanDialog} onOpenChange={setShowPlanDialog}>
        <DialogContent className="max-w-2xl max-h-[80vh] overflow-auto">
          <DialogHeader>
            <DialogTitle>Create New Plan</DialogTitle>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="plan-name">Plan Name *</Label>
              <Input
                id="plan-name"
                value={planName}
                onChange={(e) => setPlanName(e.target.value)}
                placeholder="e.g., Business Startup Plan"
                data-testid="input-dialog-plan-name"
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="plan-description">Description</Label>
              <Textarea
                id="plan-description"
                value={planDescription}
                onChange={(e) => setPlanDescription(e.target.value)}
                placeholder="Describe your plan..."
                className="min-h-[80px]"
                data-testid="input-dialog-plan-description"
              />
            </div>

            <div className="space-y-2">
              <div className="flex items-center justify-between">
                <Label>Steps (Optional)</Label>
                <Button
                  type="button"
                  variant="outline"
                  size="sm"
                  onClick={addStep}
                  data-testid="button-add-dialog-step"
                >
                  Add Step
                </Button>
              </div>
              
              <div className="space-y-2">
                {planSteps.map((step, index) => (
                  <div key={index} className="flex gap-2">
                    <Input
                      value={step}
                      onChange={(e) => updateStep(index, e.target.value)}
                      placeholder={`Step ${index + 1}`}
                      data-testid={`input-dialog-step-${index}`}
                    />
                    {planSteps.length > 1 && (
                      <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        onClick={() => removeStep(index)}
                        data-testid={`button-remove-step-${index}`}
                      >
                        ×
                      </Button>
                    )}
                  </div>
                ))}
              </div>
            </div>

            <div className="flex justify-end gap-2 pt-4">
              <Button
                variant="outline"
                onClick={() => setShowPlanDialog(false)}
                disabled={createPlanMutation.isPending}
                data-testid="button-cancel-plan"
              >
                Cancel
              </Button>
              <Button
                onClick={handleSubmitPlan}
                disabled={createPlanMutation.isPending}
                className="bg-gradient-to-r from-indigo-500 to-purple-600"
                data-testid="button-submit-dialog-plan"
              >
                {createPlanMutation.isPending ? (
                  <>
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                    Creating...
                  </>
                ) : (
                  "Create Plan"
                )}
              </Button>
            </div>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
