"use client";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import Link from "next/link";
import Layout from "@/app/components/Layout";
import {
    useGetPlanQuery,
    useUpdatePlanMutation,
    Plan,
} from "@/redux/apis/planApi";
import { useGetPlanCategoriesQuery, PlanCategory } from "@/redux/apis/planCategoryApi";
import { ArrowLeft, Save } from "lucide-react";

export default function EditPlanPage() {
    const params = useParams();
    const id = Number(params.id);

    const { data, isLoading: loadingPlan } = useGetPlanQuery(id);
    const { data: categoriesData } = useGetPlanCategoriesQuery({ includeInactive: false });

    if (loadingPlan) {
        return (
            <Layout>
                <div className="flex items-center justify-center min-h-screen">
                    <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin" />
                </div>
            </Layout>
        );
    }

    if (!data?.data) {
        return (
            <Layout>
                <div className="flex flex-col items-center justify-center min-h-screen text-red-500">
                    <p className="text-xl font-semibold">Plan not found</p>
                    <Link href="/plans" className="mt-4 text-blue-600 hover:underline">
                        Return to Plans
                    </Link>
                </div>
            </Layout>
        );
    }

    return (
        <Layout>
            <EditPlanForm
                plan={data.data}
                categories={categoriesData?.data || []}
                planId={id}
            />
        </Layout>
    );
}

interface EditPlanFormProps {
    plan: Plan;
    categories: PlanCategory[];
    planId: number;
}

function EditPlanForm({ plan, categories, planId }: EditPlanFormProps) {
    const router = useRouter();
    const [updatePlan, { isLoading: updating }] = useUpdatePlanMutation();

    const [formData, setFormData] = useState({
        name: plan.name || "",
        description: plan.description || "",
        price: String(plan.price || ""),
        originalPrice: plan.originalPrice ? String(plan.originalPrice) : "",
        currency: plan.currency || "INR",
        validity: plan.validity || 30,
        planFor: plan.planFor || "General",
        categoryId: plan.categoryId ? String(plan.categoryId) : "",
        status: plan.status || "draft",
        isActive: plan.isActive ?? true,
    });

    const handleChange = (
        e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
    ) => {
        const { name, value, type } = e.target;
        setFormData({
            ...formData,
            [name]:
                type === "checkbox" ? (e.target as HTMLInputElement).checked : value,
        });
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        try {
            await updatePlan({
                id: planId,
                data: {
                    name: formData.name,
                    description: formData.description,
                    price: Number(formData.price),
                    originalPrice: formData.originalPrice
                        ? Number(formData.originalPrice)
                        : null,
                    currency: formData.currency,
                    validity: Number(formData.validity),
                    planFor: formData.planFor,
                    categoryId: formData.categoryId ? Number(formData.categoryId) : undefined,
                    status: formData.status as "active" | "inactive" | "draft",
                    isActive: formData.isActive,
                },
            }).unwrap();

            alert("Plan updated successfully!");
            router.push(`/plans/${planId}`);
        } catch (error) {
            console.error("Failed to update plan:", error);
            alert("Failed to update plan");
        }
    };

    return (
        <div className="p-6">
            <div className="max-w-4xl mx-auto">
                <Link
                    href={`/plans/${planId}`}
                    className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6"
                >
                    <ArrowLeft className="w-5 h-5" />
                    Back to Plan Details
                </Link>

                <div className="bg-white rounded-lg shadow-sm border border-gray-200 p-8">
                    <h1 className="text-3xl font-bold text-gray-900 mb-6">
                        Edit Plan
                    </h1>

                    <form onSubmit={handleSubmit} className="space-y-6">
                        {/* Basic Information */}
                        <div className="grid md:grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Plan Name *
                                </label>
                                <input
                                    type="text"
                                    name="name"
                                    value={formData.name}
                                    onChange={handleChange}
                                    required
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                    placeholder="e.g., Premium Plan"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Status *
                                </label>
                                <select
                                    name="status"
                                    value={formData.status}
                                    onChange={handleChange}
                                    required
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                >
                                    <option value="draft">Draft</option>
                                    <option value="active">Active</option>
                                    <option value="inactive">Inactive</option>
                                </select>
                            </div>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                Category *
                            </label>
                            <select
                                name="categoryId"
                                value={formData.categoryId}
                                onChange={handleChange}
                                required
                                className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                            >
                                <option value="">Select Category</option>
                                {categories.map((category) => (
                                    <option key={category.id} value={category.id}>
                                        {category.name}
                                    </option>
                                ))}
                            </select>
                        </div>

                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-2">
                                Description *
                            </label>
                            <textarea
                                name="description"
                                value={formData.description}
                                onChange={handleChange}
                                required
                                rows={4}
                                className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none resize-none"
                                placeholder="Describe the plan benefits..."
                            />
                        </div>

                        {/* Pricing */}
                        <div className="grid md:grid-cols-3 gap-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Price *
                                </label>
                                <input
                                    type="number"
                                    name="price"
                                    value={formData.price}
                                    onChange={handleChange}
                                    required
                                    min="0"
                                    step="0.01"
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Original Price
                                </label>
                                <input
                                    type="number"
                                    name="originalPrice"
                                    value={formData.originalPrice}
                                    onChange={handleChange}
                                    min="0"
                                    step="0.01"
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Currency
                                </label>
                                <select
                                    name="currency"
                                    value={formData.currency}
                                    onChange={handleChange}
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                >
                                    <option value="INR">INR</option>
                                    <option value="USD">USD</option>
                                    <option value="EUR">EUR</option>
                                    <option value="GBP">GBP</option>
                                </select>
                            </div>
                        </div>

                        {/* Plan Details */}
                        <div className="grid md:grid-cols-2 gap-6">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Validity (Days) *
                                </label>
                                <input
                                    type="number"
                                    name="validity"
                                    value={formData.validity}
                                    onChange={handleChange}
                                    required
                                    min="1"
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Plan For *
                                </label>
                                <input
                                    type="text"
                                    name="planFor"
                                    value={formData.planFor}
                                    onChange={handleChange}
                                    required
                                    className="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none"
                                    placeholder="e.g., Beginners, Advanced Users"
                                />
                            </div>
                        </div>



                        {/* Active Status */}
                        <div className="flex items-center gap-3 p-4 border border-gray-300 rounded-lg">
                            <input
                                type="checkbox"
                                name="isActive"
                                id="isActive"
                                checked={formData.isActive}
                                onChange={handleChange}
                                className="w-5 h-5 text-blue-600 rounded"
                            />
                            <label htmlFor="isActive" className="font-medium text-gray-900">
                                Plan is active
                            </label>
                        </div>

                        {/* Submit */}
                        <div className="flex gap-4 pt-4">
                            <button
                                type="submit"
                                disabled={updating}
                                className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                <Save className="w-5 h-5" />
                                {updating ? "Updating..." : "Update Plan"}
                            </button>
                            <Link
                                href={`/plans/${planId}`}
                                className="px-6 py-3 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors"
                            >
                                Cancel
                            </Link>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
}
