"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import Layout from "@/app/components/Layout";
import {
    useGetPlansQuery,
    useDeletePlanMutation,
} from "@/redux/apis/planApi";
import { Grid, List, Edit, Trash2, Eye, Package } from "lucide-react";

export default function PlansPage() {
    const router = useRouter();
    const [filter, setFilter] = useState<"all" | "active" | "draft" | "inactive">("all");
    const [viewMode, setViewMode] = useState<"grid" | "table">("table");

    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-100 text-green-700",
            draft: "bg-yellow-100 text-yellow-700",
            inactive: "bg-red-100 text-red-700",
        };
        return statusColors[status as keyof typeof statusColors] || statusColors.draft;
    };

    return (
        <Layout>
            <div className="p-6">
                <div className="max-w-7xl mx-auto">
                    {/* Header */}
                    <div className="flex justify-between items-center mb-6">
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900">Plans Management</h1>
                            <p className="text-gray-600 mt-1">Create and manage subscription plans</p>
                        </div>
                        <div className="flex gap-4">
                            <Link
                                href="/plans/categories"
                                className="px-6 py-3 bg-white text-gray-700 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors flex items-center gap-2"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
                                </svg>
                                Categories
                            </Link>
                            <Link
                                href="/plans/create"
                                className="px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                                </svg>
                                Create Plan
                            </Link>
                        </div>
                    </div>

                    {/* Filters */}
                    <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                        <div className="flex flex-wrap gap-4 items-center justify-between">
                            <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-blue-600 text-white"
                                                : "bg-gray-100 text-gray-700 hover:bg-gray-200"
                                                }`}
                                        >
                                            {status.charAt(0).toUpperCase() + status.slice(1)}
                                        </button>
                                    ))}
                                </div>
                            </div>
                        </div>

                        {/* View Mode Toggle */}
                        <div className="flex gap-2 bg-gray-100 rounded-lg p-1">
                            <button
                                onClick={() => setViewMode("table")}
                                className={`px-3 py-2 rounded-md transition-colors flex items-center gap-2 ${viewMode === "table"
                                    ? "bg-white text-blue-600 shadow-sm"
                                    : "text-gray-600 hover:text-gray-900"
                                    }`}
                            >
                                <List className="w-4 h-4" />
                                Table
                            </button>
                            <button
                                onClick={() => setViewMode("grid")}
                                className={`px-3 py-2 rounded-md transition-colors flex items-center gap-2 ${viewMode === "grid"
                                    ? "bg-white text-blue-600 shadow-sm"
                                    : "text-gray-600 hover:text-gray-900"
                                    }`}
                            >
                                <Grid className="w-4 h-4" />
                                Grid
                            </button>
                        </div>
                    </div>

                    {/* Content */}
                    {isLoading ? (
                        <div className="text-center py-12">
                            <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin mx-auto" />
                        </div>
                    ) : error ? (
                        <div className="text-center py-12 text-red-600">
                            Failed to load plans
                        </div>
                    ) : viewMode === "table" ? (
                        /* Table View */
                        <div className="bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                            <div className="overflow-x-auto">
                                <table className="w-full">
                                    <thead className="bg-gray-50 border-b border-gray-200">
                                        <tr>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Plan
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Price
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Status
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Validity (Days)
                                            </th>
                                            <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Target Audience
                                            </th>
                                            <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                                                Actions
                                            </th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200">
                                        {data?.data.map((plan) => (
                                            <tr key={plan.id} className="hover:bg-gray-50 transition-colors">
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center gap-3">
                                                        <div>
                                                            <div className="font-semibold text-gray-900">{plan.name}</div>
                                                            <div className="text-sm text-gray-500 line-clamp-1">{plan.description}</div>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="flex items-baseline gap-2">
                                                        <span className="font-semibold text-gray-900">
                                                            {plan.currency} {plan.price}
                                                        </span>
                                                        {plan.originalPrice && plan.originalPrice > plan.price && (
                                                            <span className="text-sm text-gray-400 line-through">
                                                                {plan.originalPrice}
                                                            </span>
                                                        )}
                                                    </div>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${getStatusBadge(plan.status)}`}>
                                                        {plan.status}
                                                    </span>
                                                </td>
                                                <td className="px-6 py-4 text-gray-700">
                                                    {plan.validity} days
                                                </td>
                                                <td className="px-6 py-4">
                                                    <span className="text-sm text-gray-500">{plan.planFor}</span>
                                                </td>
                                                <td className="px-6 py-4">
                                                    <div className="flex items-center justify-end gap-2">
                                                        <Link
                                                            href={`/plans/${plan.id}`}
                                                            className="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                                                            title="View"
                                                        >
                                                            <Eye className="w-4 h-4" />
                                                        </Link>
                                                        <Link
                                                            href={`/plans/${plan.id}/edit`}
                                                            className="p-2 text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
                                                            title="Edit"
                                                        >
                                                            <Edit className="w-4 h-4" />
                                                        </Link>
                                                        <button
                                                            onClick={() => handleDelete(plan.id)}
                                                            className="p-2 text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                                                            title="Delete"
                                                        >
                                                            <Trash2 className="w-4 h-4" />
                                                        </button>
                                                    </div>
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    ) : (
                        /* Grid View */
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                            {data?.data.map((plan) => (
                                <div
                                    key={plan.id}
                                    className="bg-white rounded-lg shadow-sm border border-gray-200 p-6 hover:shadow-md transition-shadow"
                                >
                                    <div className="flex justify-between items-start mb-4">
                                        <div className="flex items-center gap-2">
                                            <h3 className="text-xl font-bold text-gray-900">
                                                {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-gray-600 text-sm mb-4 line-clamp-2">
                                        {plan.description}
                                    </p>

                                    <div className="flex items-baseline gap-2 mb-4">
                                        <span className="text-green-600">$</span>
                                        <span className="text-3xl font-bold text-gray-900">
                                            {plan.price}
                                        </span>
                                        <span className="text-gray-600">{plan.currency}</span>
                                        {plan.originalPrice && plan.originalPrice > plan.price && (
                                            <span className="text-sm text-gray-500 line-through">
                                                {plan.originalPrice}
                                            </span>
                                        )}
                                    </div>

                                    <div className="mb-4 text-sm text-gray-600 space-y-1">
                                        <p><span className="font-medium">Validity:</span> {plan.validity} days</p>
                                        <p><span className="font-medium">For:</span> {plan.planFor}</p>
                                    </div>

                                    <div className="flex gap-2">
                                        <Link
                                            href={`/plans/${plan.id}`}
                                            className="flex-1 flex items-center justify-center gap-2 px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors text-gray-700"
                                        >
                                            <Eye className="w-4 h-4" />
                                            View
                                        </Link>
                                        <Link
                                            href={`/plans/${plan.id}/edit`}
                                            className="flex items-center justify-center gap-2 px-4 py-2 bg-blue-100 text-blue-700 rounded-lg hover:bg-blue-200 transition-colors"
                                        >
                                            <Edit className="w-4 h-4" />
                                        </Link>
                                        <button
                                            onClick={() => handleDelete(plan.id)}
                                            className="flex items-center justify-center gap-2 px-4 py-2 bg-red-100 text-red-700 rounded-lg hover:bg-red-200 transition-colors"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}

                    {data?.data.length === 0 && (
                        <div className="text-center py-12">
                            <Package className="w-16 h-16 text-gray-400 mx-auto mb-4" />
                            <p className="text-gray-600">No plans found</p>
                        </div>
                    )}
                </div>
            </div>
        </Layout>
    );
}
