"use client";

import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useRouter } from "next/navigation";
import Link from "next/link";
import Layout from "@/app/components/Layout";
import { useCreatePlanCategoryMutation } from "@/redux/apis/planCategoryApi";
import { ArrowLeft, Save } from "lucide-react";

const schema = yup.object({
    name: yup.string().required("Category name is required"),
    description: yup.string().optional(),
    isActive: yup.boolean().default(true),
});

type FormData = yup.InferType<typeof schema>;

export default function CreatePlanCategoryPage() {
    const router = useRouter();
    const [createCategory, { isLoading }] = useCreatePlanCategoryMutation();

    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm({
        resolver: yupResolver(schema),
        defaultValues: {
            isActive: true,
        },
    });

    const onSubmit = async (data: any) => {
        try {
            await createCategory(data).unwrap();
            alert("Category created successfully");
            router.push("/plans/categories");
        } catch (error: any) {
            console.error("Failed to create category:", error);
            alert(error?.data?.message || "Failed to create category");
        }
    };

    return (
        <Layout>
            <div className="p-6">
                <div className="max-w-2xl mx-auto">
                    <Link
                        href="/plans/categories"
                        className="inline-flex items-center gap-2 text-gray-600 hover:text-gray-900 mb-6"
                    >
                        <ArrowLeft className="w-5 h-5" />
                        Back to Categories
                    </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">Create Category</h1>

                        <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                            {/* Name */}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Name *
                                </label>
                                <input
                                    type="text"
                                    {...register("name")}
                                    className={`w-full px-4 py-3 rounded-lg border ${errors.name ? "border-red-500" : "border-gray-300"
                                        } focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:outline-none`}
                                    placeholder="e.g., Solar Installation"
                                />
                                {errors.name && (
                                    <p className="mt-1 text-sm text-red-500">{errors.name.message}</p>
                                )}
                            </div>

                            {/* Description */}
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-2">
                                    Description
                                </label>
                                <textarea
                                    {...register("description")}
                                    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="Optional description..."
                                />
                                {errors.description && (
                                    <p className="mt-1 text-sm text-red-500">{errors.description.message}</p>
                                )}
                            </div>

                            {/* Is Active */}
                            <div className="flex items-center">
                                <label className="flex items-center gap-2 cursor-pointer">
                                    <input
                                        type="checkbox"
                                        {...register("isActive")}
                                        className="w-5 h-5 text-blue-600 rounded border-gray-300 focus:ring-blue-500"
                                    />
                                    <span className="text-gray-700 font-medium">Active</span>
                                </label>
                            </div>

                            {/* Actions */}
                            <div className="flex gap-4 pt-4">
                                <button
                                    type="submit"
                                    disabled={isLoading}
                                    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" />
                                    {isLoading ? "Creating..." : "Create Category"}
                                </button>
                                <Link
                                    href="/plans/categories"
                                    className="px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors"
                                >
                                    Cancel
                                </Link>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </Layout>
    );
}
