import { useState, type MouseEvent } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useLocation } from "wouter";
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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  Target,
  TrendingUp,
  Sparkles,
  Plus,
  CheckCircle2,
  Clock,
  Brain,
  Search,
  Trash2,
  ChevronRight,
  ChevronDown,
  Circle,
} from "lucide-react";
import { Progress } from "@/components/ui/progress";

function PlanSteps({ planId }: { planId: string }) {
  const { data: steps = [], isLoading } = useQuery<PlanStep[]>({
    queryKey: ["/api/plans", planId, "steps"],
    enabled: !!planId,
  });

  if (isLoading) {
    return (
      <div className="mt-3 pt-3 border-t border-white/10">
        <p className="text-xs text-muted-foreground">Loading steps...</p>
      </div>
    );
  }

  if (steps.length === 0) {
    return (
      <div className="mt-3 pt-3 border-t border-white/10">
        <p className="text-xs text-muted-foreground">No steps added yet</p>
      </div>
    );
  }

  return (
    <div className="mt-3 pt-3 border-t border-white/10 space-y-2">
      <p className="text-xs font-medium text-muted-foreground mb-2">Steps:</p>
      {steps.map((step, index) => (
        <div key={step.id} className="flex items-start gap-2 text-xs" data-testid={`step-item-${step.id}`}>
          {step.status === "completed" ? (
            <CheckCircle2 className="h-3 w-3 text-green-500 flex-shrink-0 mt-0.5" />
          ) : (
            <Circle className="h-3 w-3 text-muted-foreground flex-shrink-0 mt-0.5" />
          )}
          <span className={step.status === "completed" ? "line-through text-muted-foreground" : ""}>
            ({index + 1}) {step.stepText}
          </span>
        </div>
      ))}
    </div>
  );
}

export default function Dashboard() {
  const [, setLocation] = useLocation();
  const [searchQuery, setSearchQuery] = useState("");
  const [showCreateDialog, setShowCreateDialog] = useState(false);
  const [newPlan, setNewPlan] = useState({ planName: "", planDescription: "" });
  const [expandedPlans, setExpandedPlans] = useState<Set<string>>(new Set());

  const { data: plans = [], isLoading: plansLoading } = useQuery<Plan[]>({
    queryKey: ["/api/plans"],
  });

  const { data: stats } = useQuery<{ totalPlans: number; avgCompletion: number; aiUsageCount: number }>({
    queryKey: ["/api/user/stats"],
  });

  const createPlanMutation = useMutation({
    mutationFn: async (data: { planName: string; planDescription: string }) => {
      const res = await apiRequest("POST", "/api/plans", {
        ...data,
        progressPercent: 0,
      });
      return res.json();
    },
    onSuccess: (newPlan) => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans"] });
      queryClient.invalidateQueries({ queryKey: ["/api/user/stats"] });
      setShowCreateDialog(false);
      setNewPlan({ planName: "", planDescription: "" });
      setLocation(`/plan/${newPlan.id}`);
    },
  });

  const deletePlanMutation = useMutation({
    mutationFn: async (id: string) => {
      await apiRequest("DELETE", `/api/plans/${id}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/plans"] });
      queryClient.invalidateQueries({ queryKey: ["/api/user/stats"] });
    },
  });

  const filteredPlans = plans.filter(
    (plan) =>
      plan.planName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (plan.planDescription?.toLowerCase().includes(searchQuery.toLowerCase()) ?? false)
  );

  const activePlans = plans.filter(p => p.progressPercent > 0 && p.progressPercent < 100);
  const completedPlans = plans.filter(p => p.progressPercent === 100);

  const handleCreatePlan = () => {
    if (!newPlan.planName.trim()) return;
    createPlanMutation.mutate(newPlan);
  };

  const handleDeletePlan = (e: MouseEvent, id: string) => {
    e.stopPropagation();
    if (confirm("Are you sure you want to delete this plan?")) {
      deletePlanMutation.mutate(id);
    }
  };

  const togglePlanExpanded = (e: MouseEvent, planId: string) => {
    e.stopPropagation();
    setExpandedPlans(prev => {
      const next = new Set(prev);
      if (next.has(planId)) {
        next.delete(planId);
      } else {
        next.add(planId);
      }
      return next;
    });
  };

  if (plansLoading) {
    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 your workspace...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-background p-4 md:p-6 lg:p-8 space-y-6">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl md:text-4xl font-bold bg-gradient-to-r from-indigo-400 to-purple-400 bg-clip-text text-transparent">
            Dashboard
          </h1>
          <p className="text-muted-foreground mt-1">Welcome back! Let's achieve your goals today.</p>
        </div>
        <Button
          onClick={() => setShowCreateDialog(true)}
          className="bg-gradient-to-r from-indigo-500 to-purple-600 shadow-lg shadow-purple-500/20"
          data-testid="button-create-plan-header"
        >
          <Plus className="mr-2 h-4 w-4" />
          Create New Plan
        </Button>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {/* Total Plans Card */}
        <Card className="p-6 bg-card/50 backdrop-blur-sm border-white/10 hover:border-indigo-500/30 transition-all">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Total Plans</p>
              <p className="text-3xl font-bold mt-1">{stats?.totalPlans || 0}</p>
            </div>
            <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-indigo-500/20 to-purple-500/20 flex items-center justify-center">
              <Target className="h-6 w-6 text-indigo-400" />
            </div>
          </div>
        </Card>

        {/* Active Plans Card */}
        <Card className="p-6 bg-card/50 backdrop-blur-sm border-white/10 hover:border-purple-500/30 transition-all">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Active Plans</p>
              <p className="text-3xl font-bold mt-1">{activePlans.length}</p>
            </div>
            <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-purple-500/20 to-pink-500/20 flex items-center justify-center">
              <Clock className="h-6 w-6 text-purple-400" />
            </div>
          </div>
        </Card>

        {/* Completion Rate Card */}
        <Card className="p-6 bg-card/50 backdrop-blur-sm border-white/10 hover:border-teal-500/30 transition-all">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">Avg Completion</p>
              <p className="text-3xl font-bold mt-1">{stats?.avgCompletion || 0}%</p>
            </div>
            <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-teal-500/20 to-cyan-500/20 flex items-center justify-center">
              <TrendingUp className="h-6 w-6 text-teal-400" />
            </div>
          </div>
        </Card>

        {/* AI Usage Card */}
        <Card className="p-6 bg-card/50 backdrop-blur-sm border-white/10 hover:border-cyan-500/30 transition-all">
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-muted-foreground">AI Assists</p>
              <p className="text-3xl font-bold mt-1">{stats?.aiUsageCount || 0}</p>
            </div>
            <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-cyan-500/20 to-teal-500/20 flex items-center justify-center">
              <Sparkles className="h-6 w-6 text-cyan-400" />
            </div>
          </div>
        </Card>
      </div>

      {/* AI Recommendation Widget */}
      <Card className="p-6 bg-gradient-to-br from-cyan-500/10 to-teal-500/10 border-cyan-500/30 backdrop-blur-sm">
        <div className="flex items-start gap-4">
          <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-cyan-500/30 to-teal-500/30 flex items-center justify-center flex-shrink-0">
            <Brain className="h-6 w-6 text-cyan-400" />
          </div>
          <div className="flex-1">
            <h3 className="font-semibold text-lg mb-2">AI Recommendation</h3>
            <p className="text-muted-foreground text-sm mb-3">
              You're making great progress! Consider breaking down larger tasks into smaller steps for better completion rates.
            </p>
            <Button variant="outline" size="sm" className="border-cyan-500/30" data-testid="button-ai-insights">
              Get More Insights
            </Button>
          </div>
        </div>
      </Card>

      {/* Search Bar */}
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          type="search"
          placeholder="Search your plans..."
          className="pl-10 bg-card/50 backdrop-blur-sm border-white/10"
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          data-testid="input-search-plans"
        />
      </div>

      {/* Plans Section */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-2xl font-semibold">Your Plans</h2>
          <div className="flex gap-2 text-sm text-muted-foreground">
            <span>{filteredPlans.length} total</span>
            <span>•</span>
            <span className="text-cyan-400">{activePlans.length} active</span>
          </div>
        </div>

        {filteredPlans.length === 0 ? (
          <Card className="p-12 text-center bg-card/30 backdrop-blur-sm border-white/10">
            <div className="max-w-md mx-auto space-y-4">
              <div className="h-16 w-16 rounded-full bg-gradient-to-br from-indigo-500/20 to-purple-500/20 flex items-center justify-center mx-auto">
                <Target className="h-8 w-8 text-indigo-400" />
              </div>
              <h3 className="text-xl font-semibold">
                {searchQuery ? "No plans found" : "No plans yet"}
              </h3>
              <p className="text-muted-foreground">
                {searchQuery
                  ? "Try adjusting your search query"
                  : "Create your first plan to start organizing with AI"}
              </p>
              {!searchQuery && (
                <Button
                  onClick={() => setShowCreateDialog(true)}
                  className="bg-gradient-to-r from-indigo-500 to-purple-600"
                  data-testid="button-create-first-plan"
                >
                  <Plus className="mr-2 h-4 w-4" />
                  Create Your First Plan
                </Button>
              )}
            </div>
          </Card>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
            {filteredPlans.map((plan) => (
              <Card
                key={plan.id}
                className="p-6 bg-card/50 backdrop-blur-sm border-white/10 hover:border-purple-500/30 transition-all hover:shadow-xl hover:shadow-purple-500/10 cursor-pointer group"
                onClick={() => setLocation(`/plan/${plan.id}`)}
                data-testid={`card-plan-${plan.id}`}
              >
                <div className="space-y-4">
                  <div className="flex items-start justify-between gap-2">
                    <h3 className="font-semibold text-lg group-hover:text-primary transition-colors flex-1">
                      {plan.planName}
                    </h3>
                    <div className="flex items-center gap-2 flex-shrink-0">
                      {plan.progressPercent === 100 && (
                        <CheckCircle2 className="h-5 w-5 text-teal-400" />
                      )}
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
                        onClick={(e) => handleDeletePlan(e, plan.id)}
                        data-testid={`button-delete-plan-${plan.id}`}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                  
                  {plan.planDescription && (
                    <p className="text-sm text-muted-foreground line-clamp-2">
                      {plan.planDescription}
                    </p>
                  )}

                  <div className="space-y-2">
                    <div className="flex items-center justify-between text-sm">
                      <span className="text-muted-foreground">Progress</span>
                      <span className="font-medium">{plan.progressPercent}%</span>
                    </div>
                    <Progress value={plan.progressPercent} className="h-2" />
                  </div>

                  <div className="flex items-center justify-between text-xs text-muted-foreground">
                    <span>Updated {new Date(plan.updatedAt).toLocaleDateString()}</span>
                    <div className="flex items-center gap-2">
                      {plan.progressPercent > 0 && plan.progressPercent < 100 && (
                        <span className="text-cyan-400">In Progress</span>
                      )}
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-6 w-6"
                        onClick={(e) => togglePlanExpanded(e, plan.id)}
                        data-testid={`button-expand-plan-${plan.id}`}
                      >
                        {expandedPlans.has(plan.id) ? (
                          <ChevronDown className="h-4 w-4" />
                        ) : (
                          <ChevronRight className="h-4 w-4" />
                        )}
                      </Button>
                    </div>
                  </div>

                  {/* Steps Section (when expanded) */}
                  {expandedPlans.has(plan.id) && (
                    <PlanSteps planId={plan.id} />
                  )}
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Create Plan Dialog */}
      <Dialog open={showCreateDialog} onOpenChange={setShowCreateDialog}>
        <DialogContent className="bg-card/95 backdrop-blur-xl border-white/10">
          <DialogHeader>
            <DialogTitle>Create New Plan</DialogTitle>
            <DialogDescription>
              Start a new plan and let AI help you break it down into actionable steps
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="planName">Plan Title</Label>
              <Input
                id="planName"
                placeholder="e.g., Launch my startup"
                value={newPlan.planName}
                onChange={(e) => setNewPlan({ ...newPlan, planName: e.target.value })}
                data-testid="input-plan-title"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="planDescription">Description (Optional)</Label>
              <Textarea
                id="planDescription"
                placeholder="Add more details about your plan..."
                value={newPlan.planDescription}
                onChange={(e) => setNewPlan({ ...newPlan, planDescription: e.target.value })}
                data-testid="textarea-plan-description"
                rows={3}
              />
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setShowCreateDialog(false)} data-testid="button-cancel-plan">
              Cancel
            </Button>
            <Button
              onClick={handleCreatePlan}
              disabled={!newPlan.planName.trim() || createPlanMutation.isPending}
              className="bg-gradient-to-r from-indigo-500 to-purple-600"
              data-testid="button-submit-plan"
            >
              {createPlanMutation.isPending ? "Creating..." : "Create Plan"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
