"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import { Plus, Edit, Trash2, Eye, Package, ShoppingCart, DollarSign } from "lucide-react";
import Navbar from "@/app/components/Navbar";
import Footer from "@/app/components/Footer";
import {
    useGetPlansQuery,
    useDeletePlanMutation,
    Plan,
} from "@/redux/apis/planApi";

export default function PlansPage() {
    const router = useRouter();
    const [filter, setFilter] = useState<"all" | "active" | "draft" | "inactive">("all");
    const { data, isLoading, error } = useGetPlansQuery({
        status: filter === "all" ? undefined : filter,
        includeInactive: filter === "all" || filter === "inactive",
    });

    const [deletePlan] = useDeletePlanMutation();

    const handleDelete = async (id: number) => {
        if (confirm("Are you sure you want to deactivate this plan?")) {
            try {
                await deletePlan({ id }).unwrap();
                alert("Plan deactivated successfully");
            } catch (error) {
                console.error("Failed to delete plan:", error);
                alert("Failed to deactivate plan");
            }
        }
    };

    const getStatusBadge = (status: string) => {
        const statusColors = {
            active: "bg-green-500/20 text-green-500",
            draft: "bg-yellow-500/20 text-yellow-500",
            inactive: "bg-red-500/20 text-red-500",
        };
        return statusColors[status as keyof typeof statusColors] || statusColors.draft;
    };

    return (
        <div className="min-h-screen flex flex-col bg-[var(--background)] transition-colors duration-300">
            <Navbar />
            <main className="flex-1 pt-24 pb-16">
                <div className="w-full px-4 sm:px-6 lg:px-8 py-8">
                    <motion.div
                        initial={{ opacity: 0, y: 20 }}
                        animate={{ opacity: 1, y: 0 }}
                        transition={{ duration: 0.5 }}
                        className="max-w-7xl mx-auto"
                    >
                        {/* Header */}
                        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 mb-8">
                            <div>
                                <h1 className="text-3xl md:text-4xl font-bold text-theme-primary mb-2">
                                    Plans Management
                                </h1>
                                <p className="text-theme-secondary">
                                    Create and manage subscription plans
                                </p>
                            </div>
                            <button
                                onClick={() => router.push("/crm/plans/create")}
                                className="flex items-center gap-2 px-6 py-3 bg-primary-500 text-white rounded-xl hover:bg-primary-600 transition-colors shadow-lg"
                            >
                                <Plus className="w-5 h-5" />
                                Create Plan
                            </button>
                        </div>

                        {/* Filters */}
                        <div className="glass-card p-4 mb-6">
                            <div className="flex flex-wrap gap-4 items-center">
                                <div className="flex gap-2">
                                    {["all", "active", "draft", "inactive"].map((status) => (
                                        <button
                                            key={status}
                                            onClick={() => setFilter(status as any)}
                                            className={`px-4 py-2 rounded-lg transition-colors ${filter === status
                                                ? "bg-primary-500 text-white"
                                                : "bg-theme-input text-theme-secondary hover:bg-primary-500/10"
                                                }`}
                                        >
                                            {status.charAt(0).toUpperCase() + status.slice(1)}
                                        </button>
                                    ))}
                                </div>

                            </div>
                        </div>

                        {/* Plans Grid */}
                        {isLoading ? (
                            <div className="text-center py-12">
                                <div className="w-12 h-12 border-4 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto" />
                            </div>
                        ) : error ? (
                            <div className="text-center py-12 text-red-500">
                                Failed to load plans
                            </div>
                        ) : (
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                                {data?.data.map((plan) => (
                                    <motion.div
                                        key={plan.id}
                                        initial={{ opacity: 0, scale: 0.95 }}
                                        animate={{ opacity: 1, scale: 1 }}
                                        className="glass-card p-6 hover:shadow-xl transition-all"
                                    >
                                        <div className="flex justify-between items-start mb-4">
                                            <div className="flex items-center gap-2">

                                                <h3 className="text-xl font-bold text-theme-primary">
                                                    {plan.name}
                                                </h3>
                                            </div>
                                            <span
                                                className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusBadge(
                                                    plan.status
                                                )}`}
                                            >
                                                {plan.status}
                                            </span>
                                        </div>

                                        <p className="text-theme-secondary text-sm mb-4 line-clamp-2">
                                            {plan.description}
                                        </p>

                                        <div className="flex items-baseline gap-2 mb-4">
                                            <DollarSign className="w-5 h-5 text-primary-500" />
                                            <span className="text-3xl font-bold text-theme-primary">
                                                {plan.price}
                                            </span>
                                            <span className="text-theme-secondary">{plan.currency}</span>
                                            {plan.originalPrice && plan.originalPrice > plan.price && (
                                                <span className="text-sm text-theme-muted line-through">
                                                    {plan.originalPrice}
                                                </span>
                                            )}
                                        </div>

                                        <div className="mb-4 text-sm text-theme-secondary space-y-1">
                                            <p><span className="font-medium text-theme-primary">Validity:</span> {plan.validity} days</p>
                                            <p><span className="font-medium text-theme-primary">For:</span> {plan.planFor}</p>
                                        </div>

                                        <div className="flex gap-2">
                                            <button
                                                onClick={() => router.push(`/crm/plans/${plan.id}`)}
                                                className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-theme-input rounded-xl hover:bg-primary-500/10 transition-colors"
                                            >
                                                <Eye className="w-4 h-4" />
                                                View
                                            </button>
                                            <button
                                                onClick={() => router.push(`/crm/plans/${plan.id}/edit`)}
                                                className="flex items-center justify-center gap-2 px-4 py-2 bg-blue-500/20 text-blue-500 rounded-xl hover:bg-blue-500/30 transition-colors"
                                            >
                                                <Edit className="w-4 h-4" />
                                            </button>
                                            <button
                                                onClick={() => handleDelete(plan.id)}
                                                className="flex items-center justify-center gap-2 px-4 py-2 bg-red-500/20 text-red-500 rounded-xl hover:bg-red-500/30 transition-colors"
                                            >
                                                <Trash2 className="w-4 h-4" />
                                            </button>
                                        </div>
                                    </motion.div>
                                ))}
                            </div>
                        )}

                        {data?.data.length === 0 && (
                            <div className="text-center py-12">
                                <Package className="w-16 h-16 text-theme-muted mx-auto mb-4" />
                                <p className="text-theme-secondary">No plans found</p>
                            </div>
                        )}
                    </motion.div>
                </div>
            </main>
            <Footer />
        </div>
    );
}
