import { useState } from "react";
import { useParams, useLocation } from "wouter";
import { useQuery, useMutation } from "@tanstack/react-query";
import { queryClient, apiRequest } from "@/lib/queryClient";
import type { Plan, PlanStep } from "@shared/schema";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { 
  ArrowLeft, 
  Calendar, 
  CheckCircle2, 
  ChevronDown,
  ChevronRight,
  Circle, 
  Clock, 
  Copy,
  Plus, 
  Save,
  Sparkles, 
  Target,
  Trash2,
} from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";

export default function PlanDetail() {
  const { id } = useParams();
  const [, setLocation] = useLocation();
  const [activeTab, setActiveTab] = useState("overview");
  const [showAddStepDialog, setShowAddStepDialog] = useState(false);
  const [expandedSteps, setExpandedSteps] = useState<Set<string>>(new Set());
  const [newStep, setNewStep] = useState({
    stepText: "",
    stepDescription: "",
    status: "pending" as "pending" | "in-progress" | "completed",
  });

  // AI Help states
  const [selectedStep, setSelectedStep] = useState<string>("");
  const [aiUserPrompt, setAiUserPrompt] = useState("");
  const [aiResponse, setAiResponse] = useState("");
  const [isAiLoading, setIsAiLoading] = useState(false);
  const [showSaveDialog, setShowSaveDialog] = useState(false);
  const [saveSubject, setSaveSubject] = useState("");

  const toggleStepExpanded = (stepId: string) => {
    setExpandedSteps(prev => {
      const newSet = new Set(prev);
      if (newSet.has(stepId)) {
        newSet.delete(stepId);
      } else {
        newSet.add(stepId);
      }
      return newSet;
    });
  };

  // Fetch plan details
  const { data: plan, isLoading: planLoading } = useQuery<Plan>({
    queryKey: ["/api/plans", id],
    enabled: !!id,
  });

  // Fetch plan steps
  const { data: steps = [] } = useQuery<PlanStep[]>({
    queryKey: ["/api/plans", id, "steps"],
    enabled: !!id,
  });

  // Update plan notes mutation
  const updateNotesMutation = useMutation({
    mutationFn: async (notes: string) => {
      return apiRequest("PATCH", `/api/plans/${id}`, { notes });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans", id] });
    },
  });

  // Create step mutation
  const createStepMutation = useMutation({
    mutationFn: async (step: typeof newStep) => {
      return apiRequest("POST", `/api/plans/${id}/steps`, { ...step, planId: id });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans", id, "steps"] });
      setShowAddStepDialog(false);
      setNewStep({ stepText: "", stepDescription: "", status: "pending" });
    },
  });

  // Delete step mutation
  const deleteStepMutation = useMutation({
    mutationFn: async (stepId: string) => {
      return apiRequest("DELETE", `/api/steps/${stepId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans", id, "steps"] });
    },
  });

  // Update step status mutation
  const updateStepMutation = useMutation({
    mutationFn: async ({ stepId, status }: { stepId: string; status: string }) => {
      return apiRequest("PATCH", `/api/steps/${stepId}`, { status });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans", id, "steps"] });
    },
  });

  // AI assistance mutation
  const getAiAssistanceMutation = useMutation({
    mutationFn: async ({ stepName, userPrompt, planId }: { stepName: string; userPrompt: string; planId: string }) => {
      const res = await apiRequest("POST", "/api/ai/step-assist", { stepName, userPrompt, planId });
      return await res.json();
    },
    onSuccess: (data) => {
      setAiResponse(data.response);
    },
  });

  // Save AI response mutation
  const saveAiResponseMutation = useMutation({
    mutationFn: async (data: { planId: string; stepId: string | null; stepName: string; subject: string; userPrompt: string; aiResponse: string }) => {
      const res = await apiRequest("POST", "/api/saved-ai-responses", data);
      return await res.json();
    },
    onSuccess: () => {
      setShowSaveDialog(false);
      setSaveSubject("");
    },
  });

  const handleCreateStep = () => {
    if (!newStep.stepText.trim()) return;
    createStepMutation.mutate(newStep);
  };

  const handleDeleteStep = (stepId: string) => {
    if (confirm("Are you sure you want to delete this step?")) {
      deleteStepMutation.mutate(stepId);
    }
  };

  const handleStartAiAssist = async () => {
    if (!selectedStep || !aiUserPrompt.trim() || !id) return;
    
    const step = steps.find(s => s.id === selectedStep);
    if (!step) return;

    setIsAiLoading(true);
    getAiAssistanceMutation.mutate({
      stepName: step.stepText,
      userPrompt: aiUserPrompt,
      planId: id,
    });
    setIsAiLoading(false);
  };

  const handleCopyResponse = () => {
    navigator.clipboard.writeText(aiResponse);
  };

  const handleSaveResponse = () => {
    if (!saveSubject.trim() || !id || !selectedStep) return;

    const step = steps.find(s => s.id === selectedStep);
    if (!step) return;

    saveAiResponseMutation.mutate({
      planId: id,
      stepId: selectedStep,
      stepName: step.stepText,
      subject: saveSubject,
      userPrompt: aiUserPrompt,
      aiResponse: aiResponse,
    });
  };

  const getPriorityBadgeVariant = (priority?: string) => {
    switch (priority) {
      case "high":
        return "destructive";
      case "medium":
        return "default";
      case "low":
        return "secondary";
      default:
        return "outline";
    }
  };

  // Early return if no id
  if (!id) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="p-8 text-center">
          <h2 className="text-2xl font-bold mb-2">Invalid Plan</h2>
          <p className="text-muted-foreground mb-4">
            No plan ID provided in the URL.
          </p>
          <Button onClick={() => setLocation("/dashboard")} data-testid="button-back-dashboard">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Dashboard
          </Button>
        </Card>
      </div>
    );
  }

  if (planLoading) {
    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 plan...</p>
        </div>
      </div>
    );
  }

  if (!plan) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Card className="p-8 text-center">
          <h2 className="text-2xl font-bold mb-2">Plan Not Found</h2>
          <p className="text-muted-foreground mb-4">
            The plan you're looking for doesn't exist.
          </p>
          <Button onClick={() => setLocation("/dashboard")} data-testid="button-back-dashboard">
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Dashboard
          </Button>
        </Card>
      </div>
    );
  }

  const completedSteps = steps.filter(s => s.status === "completed").length;
  const totalSteps = steps.length;
  const progressPercentage = totalSteps > 0 ? (completedSteps / totalSteps) * 100 : 0;

  return (
    <div className="min-h-screen p-6">
      {/* Header */}
      <div className="max-w-7xl mx-auto mb-6">
        <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="flex items-start justify-between gap-4">
          <div className="flex-1">
            <h1 className="text-3xl font-bold mb-2 bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
              {plan.planName}
            </h1>
            <p className="text-muted-foreground">{plan.planDescription}</p>
            
            <div className="flex flex-wrap gap-2 mt-4">
              {plan.category && (
                <Badge variant="outline" data-testid="badge-category">
                  {plan.category}
                </Badge>
              )}
              {plan.priority && (
                <Badge variant={getPriorityBadgeVariant(plan.priority)} data-testid="badge-priority">
                  {plan.priority}
                </Badge>
              )}
              {plan.targetDate && (
                <Badge variant="outline" data-testid="badge-target-date">
                  <Calendar className="mr-1 h-3 w-3" />
                  {new Date(plan.targetDate).toLocaleDateString()}
                </Badge>
              )}
            </div>
          </div>

          <Card className="p-4 bg-gradient-to-br from-indigo-500/10 to-purple-600/10 backdrop-blur-sm border-indigo-500/20">
            <div className="text-center">
              <div className="text-3xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
                {Math.round(progressPercentage)}%
              </div>
              <p className="text-sm text-muted-foreground">Complete</p>
              <Progress value={progressPercentage} className="mt-2 h-2" />
            </div>
          </Card>
        </div>
      </div>

      {/* Tabs */}
      <div className="max-w-7xl mx-auto">
        <Tabs value={activeTab} onValueChange={setActiveTab}>
          <TabsList className="grid w-full grid-cols-4 mb-6">
            <TabsTrigger value="overview" data-testid="tab-overview">Overview</TabsTrigger>
            <TabsTrigger value="steps" data-testid="tab-steps">Steps ({totalSteps})</TabsTrigger>
            <TabsTrigger value="notes" data-testid="tab-notes">Notes</TabsTrigger>
            <TabsTrigger value="ai-help" data-testid="tab-ai-help">AI Help</TabsTrigger>
          </TabsList>

          {/* Overview Tab */}
          <TabsContent value="overview" className="space-y-4">
            <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
              <Card className="p-6">
                <div className="flex items-center gap-3 mb-2">
                  <Target className="h-5 w-5 text-indigo-500" />
                  <h3 className="font-semibold">Goal</h3>
                </div>
                <p className="text-sm text-muted-foreground">
                  {plan.planDescription || "No description provided"}
                </p>
              </Card>

              <Card className="p-6">
                <div className="flex items-center gap-3 mb-2">
                  <Calendar className="h-5 w-5 text-purple-500" />
                  <h3 className="font-semibold">Target Date</h3>
                </div>
                <p className="text-sm text-muted-foreground">
                  {plan.targetDate
                    ? new Date(plan.targetDate).toLocaleDateString("en-US", {
                        month: "long",
                        day: "numeric",
                        year: "numeric",
                      })
                    : "No target date set"}
                </p>
              </Card>

              <Card className="p-6">
                <div className="flex items-center gap-3 mb-2">
                  <CheckCircle2 className="h-5 w-5 text-teal-500" />
                  <h3 className="font-semibold">Progress</h3>
                </div>
                <p className="text-sm text-muted-foreground">
                  {completedSteps} of {totalSteps} steps completed
                </p>
              </Card>
            </div>

            <Card className="p-6">
              <h3 className="font-semibold mb-4">Recent Activity</h3>
              <div className="space-y-3">
                {steps.slice(0, 5).map((step) => (
                  <div key={step.id} className="flex items-center gap-3">
                    {step.status === "completed" ? (
                      <CheckCircle2 className="h-4 w-4 text-green-500 flex-shrink-0" />
                    ) : step.status === "in-progress" ? (
                      <Clock className="h-4 w-4 text-yellow-500 flex-shrink-0" />
                    ) : (
                      <Circle className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                    )}
                    <span className="text-sm flex-1">{step.stepText}</span>
                    <Badge variant="outline" className="text-xs">
                      {step.status}
                    </Badge>
                  </div>
                ))}
                {steps.length === 0 && (
                  <p className="text-sm text-muted-foreground text-center py-4">
                    No steps added yet
                  </p>
                )}
              </div>
            </Card>
          </TabsContent>

          {/* Steps Tab */}
          <TabsContent value="steps" className="space-y-4">
            <div className="flex justify-between items-center">
              <h3 className="text-lg font-semibold">All Steps</h3>
              <Button
                onClick={() => setShowAddStepDialog(true)}
                className="bg-gradient-to-r from-indigo-500 to-purple-600"
                data-testid="button-add-step"
              >
                <Plus className="mr-2 h-4 w-4" />
                Add Step
              </Button>
            </div>

            <div className="space-y-3">
              {steps.map((step, index) => (
                <Card
                  key={step.id}
                  className="p-4 hover-elevate transition-all group"
                  data-testid={`card-step-${step.id}`}
                >
                  <div className="flex items-start gap-4">
                    <button
                      onClick={() =>
                        updateStepMutation.mutate({
                          stepId: step.id,
                          status: step.status === "completed" ? "pending" : "completed",
                        })
                      }
                      className="mt-1"
                      data-testid={`button-toggle-step-${step.id}`}
                    >
                      {step.status === "completed" ? (
                        <CheckCircle2 className="h-5 w-5 text-green-500" />
                      ) : (
                        <Circle className="h-5 w-5 text-muted-foreground" />
                      )}
                    </button>
                    
                    <div className="flex-1">
                      <button
                        onClick={() => toggleStepExpanded(step.id)}
                        className="flex items-center gap-2 w-full text-left group/title hover-elevate active-elevate-2 p-2 -ml-2 rounded-md transition-all"
                        data-testid={`button-expand-step-${step.id}`}
                      >
                        {expandedSteps.has(step.id) ? (
                          <ChevronDown className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                        ) : (
                          <ChevronRight className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                        )}
                        <h4 className="font-medium flex-1">({index + 1}) {step.stepText}</h4>
                      </button>
                      
                      {expandedSteps.has(step.id) && step.stepDescription && (
                        <div className="mt-3 pl-6 pr-2 py-3 rounded-lg bg-muted/30 border border-border/50">
                          <div className="text-sm text-foreground whitespace-pre-wrap leading-relaxed">
                            {step.stepDescription}
                          </div>
                        </div>
                      )}
                      
                      {step.dueDate && (
                        <p className="text-xs text-muted-foreground mt-2 ml-6 flex items-center gap-1">
                          <Calendar className="h-3 w-3" />
                          Due: {new Date(step.dueDate).toLocaleDateString()}
                        </p>
                      )}
                    </div>

                    <div className="flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <Select
                        value={step.status}
                        onValueChange={(status) =>
                          updateStepMutation.mutate({ stepId: step.id, status })
                        }
                      >
                        <SelectTrigger className="w-32" data-testid={`select-status-${step.id}`}>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="pending">Pending</SelectItem>
                          <SelectItem value="in-progress">In Progress</SelectItem>
                          <SelectItem value="completed">Completed</SelectItem>
                        </SelectContent>
                      </Select>
                      
                      <Button
                        variant="ghost"
                        size="icon"
                        onClick={() => handleDeleteStep(step.id)}
                        data-testid={`button-delete-step-${step.id}`}
                      >
                        <Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}
              
              {steps.length === 0 && (
                <Card className="p-12 text-center">
                  <Circle className="h-12 w-12 text-muted-foreground mx-auto mb-4 opacity-50" />
                  <h3 className="text-lg font-semibold mb-2">No Steps Yet</h3>
                  <p className="text-muted-foreground mb-4">
                    Break down your plan into actionable steps
                  </p>
                  <Button
                    onClick={() => setShowAddStepDialog(true)}
                    className="bg-gradient-to-r from-indigo-500 to-purple-600"
                    data-testid="button-add-first-step"
                  >
                    <Plus className="mr-2 h-4 w-4" />
                    Add Your First Step
                  </Button>
                </Card>
              )}
            </div>
          </TabsContent>

          {/* Notes Tab */}
          <TabsContent value="notes">
            <Card className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h3 className="text-lg font-semibold">Plan Notes</h3>
                <Button
                  onClick={() => {
                    const textarea = document.querySelector('textarea[data-testid="textarea-notes"]') as HTMLTextAreaElement;
                    if (textarea) {
                      updateNotesMutation.mutate(textarea.value);
                    }
                  }}
                  disabled={updateNotesMutation.isPending}
                  data-testid="button-save-notes"
                >
                  {updateNotesMutation.isPending ? "Saving..." : "Save Notes"}
                </Button>
              </div>
              <Textarea
                defaultValue={plan.notes || ""}
                placeholder="Add notes, ideas, resources, or anything else related to this plan..."
                className="min-h-[400px] resize-none"
                data-testid="textarea-notes"
              />
            </Card>
          </TabsContent>

          {/* AI Help Tab */}
          <TabsContent value="ai-help">
            <Card className="p-6 bg-gradient-to-br from-indigo-500/10 to-purple-600/10 backdrop-blur-sm border-indigo-500/20">
              <div className="flex items-center gap-3 mb-6">
                <Sparkles className="h-6 w-6 text-indigo-400" />
                <h3 className="text-lg font-semibold">AI Assistant</h3>
              </div>
              
              <div className="space-y-4">
                <p className="text-sm text-muted-foreground">
                  Get intelligent assistance for your plan steps
                </p>

                {/* Step Dropdown */}
                <div>
                  <label className="text-sm font-medium mb-2 block">Select Step</label>
                  <Select value={selectedStep} onValueChange={setSelectedStep}>
                    <SelectTrigger className="w-full" data-testid="select-ai-step">
                      <SelectValue placeholder="Choose a step to get help with" />
                    </SelectTrigger>
                    <SelectContent>
                      {steps.map((step, index) => (
                        <SelectItem key={step.id} value={step.id}>
                          ({index + 1}) {step.stepText}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>

                {/* Text Area */}
                <div>
                  <label className="text-sm font-medium mb-2 block">Your Question or Request</label>
                  <Textarea
                    value={aiUserPrompt}
                    onChange={(e) => setAiUserPrompt(e.target.value)}
                    placeholder="What do you need help with for this step?"
                    className="w-full resize-none"
                    style={{ width: "700px", maxWidth: "100%", height: "260px" }}
                    data-testid="textarea-ai-prompt"
                  />
                </div>

                {/* Start Button */}
                <Button
                  onClick={handleStartAiAssist}
                  disabled={!selectedStep || !aiUserPrompt.trim() || isAiLoading || getAiAssistanceMutation.isPending}
                  className="bg-gradient-to-r from-indigo-500 to-purple-600"
                  data-testid="button-ai-start"
                >
                  {isAiLoading || getAiAssistanceMutation.isPending ? "Generating..." : "Start"}
                </Button>

                {/* AI Response */}
                {aiResponse && (
                  <div className="mt-6 p-4 bg-background/50 rounded-lg border border-border/50">
                    <div className="flex items-center justify-between mb-3">
                      <h4 className="font-semibold">AI Response:</h4>
                      <div className="flex gap-2">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={handleCopyResponse}
                          data-testid="button-copy-response"
                        >
                          <Copy className="h-4 w-4 mr-1" />
                          Copy
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => setShowSaveDialog(true)}
                          data-testid="button-save-this"
                        >
                          <Save className="h-4 w-4 mr-1" />
                          Save This
                        </Button>
                      </div>
                    </div>
                    <div className="text-sm whitespace-pre-wrap leading-relaxed">
                      {aiResponse}
                    </div>
                  </div>
                )}
              </div>
            </Card>
          </TabsContent>
        </Tabs>
      </div>

      {/* Add Step Dialog */}
      <Dialog open={showAddStepDialog} onOpenChange={setShowAddStepDialog}>
        <DialogContent data-testid="dialog-add-step">
          <DialogHeader>
            <DialogTitle>Add New Step</DialogTitle>
            <DialogDescription>
              Break down your plan into actionable steps
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium mb-2 block">Step Name *</label>
              <Input
                value={newStep.stepText}
                onChange={(e) => setNewStep({ ...newStep, stepText: e.target.value })}
                placeholder="e.g., Research market trends"
                data-testid="input-step-name"
              />
            </div>
            
            <div>
              <label className="text-sm font-medium mb-2 block">Description</label>
              <Textarea
                value={newStep.stepDescription}
                onChange={(e) => setNewStep({ ...newStep, stepDescription: e.target.value })}
                placeholder="Add more details about this step..."
                rows={3}
                data-testid="textarea-step-description"
              />
            </div>

            <div>
              <label className="text-sm font-medium mb-2 block">Status</label>
              <Select
                value={newStep.status}
                onValueChange={(value: any) => setNewStep({ ...newStep, status: value })}
              >
                <SelectTrigger data-testid="select-step-status">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="pending">Pending</SelectItem>
                  <SelectItem value="in-progress">In Progress</SelectItem>
                  <SelectItem value="completed">Completed</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowAddStepDialog(false)}
              data-testid="button-cancel-step"
            >
              Cancel
            </Button>
            <Button
              onClick={handleCreateStep}
              disabled={!newStep.stepText.trim() || createStepMutation.isPending}
              className="bg-gradient-to-r from-indigo-500 to-purple-600"
              data-testid="button-create-step"
            >
              {createStepMutation.isPending ? "Adding..." : "Add Step"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Save AI Response Dialog */}
      <Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
        <DialogContent data-testid="dialog-save-ai-response">
          <DialogHeader>
            <DialogTitle>Save AI Response</DialogTitle>
            <DialogDescription>
              Give this AI response a subject/label for easy reference later
            </DialogDescription>
          </DialogHeader>
          
          <div className="space-y-4 py-4">
            <div>
              <label className="text-sm font-medium mb-2 block">Subject/Label *</label>
              <Input
                value={saveSubject}
                onChange={(e) => setSaveSubject(e.target.value)}
                placeholder="e.g., Office setup guidance"
                data-testid="input-save-subject"
              />
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowSaveDialog(false)}
              data-testid="button-cancel-save"
            >
              Cancel
            </Button>
            <Button
              onClick={handleSaveResponse}
              disabled={!saveSubject.trim() || saveAiResponseMutation.isPending}
              className="bg-gradient-to-r from-indigo-500 to-purple-600"
              data-testid="button-save-confirm"
            >
              {saveAiResponseMutation.isPending ? "Saving..." : "Save Confirm"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
