"use client";

import { useState } from "react";
import Layout from "../../components/Layout";
import {
    useGetLoanProductsQuery,
    useCreateLoanProductMutation,
    useUpdateLoanProductMutation,
    useDeleteLoanProductMutation,
    type LoanProduct
} from "@/redux/apis/financeApi";
import { useForm, SubmitHandler, Resolver, FieldValues } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Edit2, Trash2, Plus, X } from "lucide-react";

// Schema
const productSchema: yup.ObjectSchema<ProductFormData> = yup.object({
    name: yup.string().required("Name is required"),
    usefulFor: yup.string().required("Useful For is required"),
    bestFor: yup.string().required("Best For is required"),
    eligibilityCriteria: yup.string().required("Eligibility Criteria is required"),
    terms: yup.string().required("Terms are required"),
    security: yup.string().required("Security info is required"),
    iconName: yup.string().optional(),
    isActive: yup.boolean().required().default(true),
}) as yup.ObjectSchema<ProductFormData>;


interface ProductFormData {
    name: string;
    usefulFor: string;
    bestFor: string;
    eligibilityCriteria: string;
    terms: string;
    security: string;
    iconName?: string;
    isActive: boolean;
}

export default function LoanProductsPage() {
    const { data: response, isLoading } = useGetLoanProductsQuery({ includeInactive: true });
    const [createProduct] = useCreateLoanProductMutation();
    const [updateProduct] = useUpdateLoanProductMutation();
    const [deleteProduct] = useDeleteLoanProductMutation();

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingProduct, setEditingProduct] = useState<LoanProduct | null>(null);

    const { register, handleSubmit, reset, formState: { errors, isSubmitting }, setValue } = useForm<ProductFormData>({
        resolver: yupResolver(productSchema) as Resolver<ProductFormData>,
        defaultValues: {
            name: "",
            usefulFor: "",
            bestFor: "",
            eligibilityCriteria: "",
            terms: "",
            security: "",
            iconName: "",
            isActive: true,
        }
    });

    const openCreateModal = () => {
        setEditingProduct(null);
        reset({ isActive: true, iconName: "" }); // Reset form
        setIsModalOpen(true);
    };

    const openEditModal = (product: LoanProduct) => {
        setEditingProduct(product);
        // Set form values
        setValue("name", product.name);
        setValue("usefulFor", product.usefulFor);
        setValue("bestFor", product.bestFor);
        setValue("eligibilityCriteria", product.eligibilityCriteria);
        setValue("terms", product.terms);
        setValue("security", product.security);
        setValue("iconName", product.iconName || "");
        setValue("isActive", product.isActive);
        setIsModalOpen(true);
    };

    const onSubmit: SubmitHandler<FieldValues> = async (rawData) => {
        const data = rawData as ProductFormData;
        try {
            const payload = {
                ...data,
                iconName: data.iconName || undefined
            };
            if (editingProduct) {
                await updateProduct({ id: editingProduct.id, data: payload }).unwrap();
            } else {
                await createProduct(payload).unwrap();
            }
            setIsModalOpen(false);
            reset();
        } catch (error) {
            console.error("Failed to save product", error);
            alert("Failed to save product");
        }
    };

    const handleDelete = async (id: number) => {
        if (confirm("Are you sure you want to delete this product?")) {
            try {
                await deleteProduct(id).unwrap();
            } catch (error) {
                console.error("Failed to delete product", error);
                alert("Failed to delete product");
            }
        }
    };

    return (
        <Layout>
            <div className="flex flex-col h-full bg-gray-50">
                {/* Header Toolbar - Sticky */}
                {/* Header Toolbar - Sticky */}
                <div className="bg-white border-b border-gray-200 sticky top-0 z-20 px-4 md:px-6 py-4 shadow-sm flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
                    <div>
                        <h1 className="text-xl font-bold text-gray-900 tracking-tight">Loan Products</h1>
                        <p className="text-sm text-gray-500 mt-0.5">Manage available loan options for customers.</p>
                    </div>
                    <button
                        onClick={openCreateModal}
                        className="w-full sm:w-auto flex items-center justify-center gap-2 px-4 py-2.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors shadow-sm focus:ring-4 focus:ring-blue-100 active:transform active:scale-95"
                    >
                        <Plus className="w-4 h-4" />
                        Add Product
                    </button>
                </div>

                {/* Content */}
                {/* Content */}
                <div className="flex-1 p-4 md:p-6 overflow-hidden flex flex-col">
                    {isLoading ? (
                         <div className="flex-1 flex items-center justify-center text-gray-500">
                             <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mr-3"></div>
                             Loading products...
                         </div>
                    ) : response?.data.length === 0 ? (
                        <div className="flex-1 flex flex-col items-center justify-center text-gray-500">
                            <div className="bg-gray-100 p-4 rounded-full mb-4">
                                <Plus className="w-8 h-8 text-gray-400" />
                            </div>
                            <h3 className="text-lg font-medium text-gray-900">No products found</h3>
                            <p className="text-sm mt-1">Get started by creating a new loan product.</p>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 md:gap-6 overflow-y-auto pb-20 md:pb-0">
                            {response?.data.map((product) => (
                                <div key={product.id} className="bg-white rounded-xl shadow-sm border border-gray-200 hover:shadow-md transition-shadow flex flex-col overflow-hidden group">
                                    <div className="p-5 flex-1">
                                        <div className="flex justify-between items-start mb-4">
                                            <div>
                                                <h3 className="text-lg font-bold text-gray-900 group-hover:text-blue-600 transition-colors">{product.name}</h3>
                                                {product.iconName && (
                                                    <span className="inline-block mt-1 text-xs font-mono bg-gray-100 px-1.5 py-0.5 rounded text-gray-500">
                                                        {product.iconName}
                                                    </span>
                                                )}
                                            </div>
                                            <span className={`px-2.5 py-1 rounded-full text-xs font-medium border ${product.isActive ? 'bg-green-50 text-green-700 border-green-100' : 'bg-gray-50 text-gray-600 border-gray-200'}`}>
                                                {product.isActive ? 'Active' : 'Inactive'}
                                            </span>
                                        </div>
                                        
                                        <div className="space-y-3">
                                            <div>
                                                <div className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Best For</div>
                                                <p className="text-sm text-gray-700 line-clamp-2">{product.bestFor}</p>
                                            </div>
                                            <div>
                                                <div className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Useful For</div>
                                                <p className="text-sm text-gray-700 line-clamp-2">{product.usefulFor}</p>
                                            </div>
                                            <div>
                                                <div className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1">Terms</div>
                                                <p className="text-sm text-gray-700 line-clamp-2">{product.terms}</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div className="px-5 py-3 bg-gray-50 border-t border-gray-100 flex justify-end gap-2">
                                        <button 
                                            onClick={() => openEditModal(product)} 
                                            className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-lg transition-colors"
                                        >
                                            <Edit2 className="w-4 h-4" />
                                            Edit
                                        </button>
                                        <button 
                                            onClick={() => handleDelete(product.id)} 
                                            className="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-red-600 hover:text-red-700 hover:bg-red-50 rounded-lg transition-colors"
                                        >
                                            <Trash2 className="w-4 h-4" />
                                            Delete
                                        </button>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* Modal */}
                {isModalOpen && (
                    <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center sm:p-4 bg-black/50 backdrop-blur-sm">
                        <div className="bg-white w-full h-[90vh] sm:h-auto sm:max-h-[90vh] sm:rounded-xl shadow-xl overflow-hidden flex flex-col rounded-t-2xl">
                            <div className="p-5 border-b border-gray-200 flex justify-between items-center bg-white shrink-0">
                                <h2 className="text-lg font-bold text-gray-900">
                                    {editingProduct ? "Edit Product" : "New Loan Product"}
                                </h2>
                                <button onClick={() => setIsModalOpen(false)} className="text-gray-400 hover:text-gray-600 transition-colors p-2 rounded-full hover:bg-gray-100">
                                    <X className="w-5 h-5" />
                                </button>
                            </div>

                            <form onSubmit={handleSubmit(onSubmit)} className="p-5 space-y-5 overflow-y-auto flex-1">
                                <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1.5">Product Name</label>
                                        <input {...register("name")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all" />
                                        {errors.name && <p className="text-red-500 text-xs mt-1">{errors.name.message}</p>}
                                    </div>
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1.5">Icon Name (Lucide)</label>
                                        <input {...register("iconName")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all" placeholder="e.g. Briefcase" />
                                    </div>
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1.5">Useful For?</label>
                                    <input {...register("usefulFor")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all" placeholder="e.g. Expanding business operations" />
                                    {errors.usefulFor && <p className="text-red-500 text-xs mt-1">{errors.usefulFor.message}</p>}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1.5">Best For?</label>
                                    <input {...register("bestFor")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all" placeholder="e.g. Established businesses" />
                                    {errors.bestFor && <p className="text-red-500 text-xs mt-1">{errors.bestFor.message}</p>}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1.5">Eligibility Criteria</label>
                                    <textarea {...register("eligibilityCriteria")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all resize-none" rows={3} />
                                    {errors.eligibilityCriteria && <p className="text-red-500 text-xs mt-1">{errors.eligibilityCriteria.message}</p>}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1.5">Terms</label>
                                    <textarea {...register("terms")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all resize-none" rows={3} />
                                    {errors.terms && <p className="text-red-500 text-xs mt-1">{errors.terms.message}</p>}
                                </div>

                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-1.5">Security</label>
                                    <input {...register("security")} className="w-full px-3.5 py-2.5 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-gray-900 bg-white placeholder-gray-400 transition-all" />
                                    {errors.security && <p className="text-red-500 text-xs mt-1">{errors.security.message}</p>}
                                </div>

                                <div className="flex items-center gap-2 py-1">
                                    <input type="checkbox" id="isActive" {...register("isActive")} className="w-5 h-5 text-blue-600 rounded border-gray-300 focus:ring-blue-500" />
                                    <label htmlFor="isActive" className="text-sm font-medium text-gray-700 select-none">Active Product</label>
                                </div>

                                <div className="pt-2 flex flex-col-reverse sm:flex-row justify-end gap-3 pb-safe">
                                    <button type="button" onClick={() => setIsModalOpen(false)} className="w-full sm:w-auto px-5 py-2.5 text-gray-700 bg-gray-100 font-medium rounded-lg hover:bg-gray-200 transition-colors">
                                        Cancel
                                    </button>
                                    <button type="submit" disabled={isSubmitting} className="w-full sm:w-auto px-5 py-2.5 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors shadow-sm shadow-blue-200">
                                        {isSubmitting ? "Saving..." : "Save Product"}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                )}
            </div>
        </Layout>
    );
}
