"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { Building2, Save, X, Upload, MapPin, Check, AlertCircle, Camera, UserCircle } from "lucide-react";
import {
    useGetShopRegistrationQuery,
    useCreateShopRegistrationMutation,
    useUpdateShopRegistrationMutation,
} from "@/redux/apis/shopApi";
import GoogleMapLocationPicker, { LocationDetails } from "../GoogleMapLocationPicker";

export default function ShopRegistrationForm({ onClose }: { onClose?: () => void }) {
    const router = useRouter();
    const { data, isLoading } = useGetShopRegistrationQuery();
    const [createShop] = useCreateShopRegistrationMutation();
    const [updateShop] = useUpdateShopRegistrationMutation();

    const [formData, setFormData] = useState({
        ownerName: "",
        shopName: "",
        emailId: "",
        shopNo: "",
        complexName: "",
        street: "",
        landmark: "",
        city: "",
        pinCode: "",
        mobileNumber: "",
        mobileNumber2: "",
        shopGoogleLocation: "",
    });


    const [files, setFiles] = useState<Record<string, File | File[] | null>>({
        shopPhotos: null,
        selfiePhoto: null,
        shopactDocument: null,
        udyamAadharDocument: null,
        gstDocument: null,
        aadharCard: null,
        panCard: null,
        ownerPassportPhoto: null,
    });

    const [isSubmitting, setIsSubmitting] = useState(false);

    useEffect(() => {
        if (data?.success && data.data) {
            setFormData({
                ownerName: data.data.ownerName || "",
                shopName: data.data.shopName || "",
                emailId: data.data.emailId || "",
                shopNo: data.data.shopNo || "",
                complexName: data.data.complexName || "",
                street: data.data.street || "",
                landmark: data.data.landmark || "",
                city: data.data.city || "",
                pinCode: data.data.pinCode || "",
                mobileNumber: data.data.mobileNumber || "",
                mobileNumber2: data.data.mobileNumber2 || "",
                shopGoogleLocation: data.data.shopGoogleLocation || "",
            });
        }
    }, [data]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
        setFormData({
            ...formData,
            [e.target.name]: e.target.value,
        });
    };

    const handleLocationChange = (location: string, lat?: number, lng?: number, details?: LocationDetails) => {
        setFormData(prev => ({
            ...prev,
            shopGoogleLocation: location,
            city: details?.city || details?.locality || prev.city,
            pinCode: details?.pincode || prev.pinCode,
            street: !prev.street && details?.address ? details.address.split(',')[0] : prev.street
        }));
    };

    const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name } = e.target;
        if (name === "shopPhotos" && e.target.files) {
            setFiles({ ...files, [name]: Array.from(e.target.files) });
        } else if (e.target.files?.[0]) {
            setFiles({ ...files, [name]: e.target.files[0] });
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);

        try {
            const submitData = new FormData();

            Object.keys(formData).forEach((key) => {
                if (formData[key as keyof typeof formData]) {
                    submitData.append(key, formData[key as keyof typeof formData]);
                }
            });

            // Handle shop photos - map to shopImage1, shopImage2, etc.
            if (files.shopPhotos && Array.isArray(files.shopPhotos)) {
                files.shopPhotos.forEach((file, index) => {
                    if (index < 5) {
                        submitData.append(`shopImage${index + 1}`, file);
                    }
                });
            }

            // Handle other files with key mapping
            Object.keys(files).forEach((key) => {
                if (key !== "shopPhotos" && files[key]) {
                    const file = Array.isArray(files[key]) ? files[key][0] : files[key];
                    if (file) {
                        // Map specific keys if needed
                        let backendKey = key;
                        if (key === "selfiePhoto") backendKey = "selfie";

                        submitData.append(backendKey, file);
                    }
                }
            });

            if (data?.success && data.data?.id) {
                await updateShop(submitData).unwrap();
            } else {
                await createShop(submitData).unwrap();
            }
            if (onClose) onClose();
            router.refresh();
        } catch (error) {
            console.error("Error saving shop registration:", error);
            alert("Failed to save shop registration");
        } finally {
            setIsSubmitting(false);
        }
    };

    if (isLoading) {
        return <div className="text-center py-4">Loading...</div>;
    }

    return (
        <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid md:grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Owner Name *
                    </label>
                    <input
                        type="text"
                        name="ownerName"
                        value={formData.ownerName}
                        onChange={handleChange}
                        required
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Shop Name *
                    </label>
                    <input
                        type="text"
                        name="shopName"
                        value={formData.shopName}
                        onChange={handleChange}
                        required
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Email <span className="text-theme-muted text-xs ms-1">(Optional)</span>
                    </label>
                    <input
                        type="email"
                        name="emailId"
                        value={formData.emailId}
                        onChange={handleChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                        placeholder="Enter shop email"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Mobile Number <span className="text-theme-muted text-xs ms-1">(Optional)</span>
                    </label>
                    <input
                        type="tel"
                        name="mobileNumber"
                        value={formData.mobileNumber}
                        onChange={handleChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                        placeholder="Enter shop mobile number"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Shop No
                    </label>
                    <input
                        type="text"
                        name="shopNo"
                        value={formData.shopNo}
                        onChange={handleChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Complex Name
                    </label>
                    <input
                        type="text"
                        name="complexName"
                        value={formData.complexName}
                        onChange={handleChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Street
                    </label>
                    <input
                        type="text"
                        name="street"
                        value={formData.street}
                        onChange={handleChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        City
                    </label>
                    <input
                        type="text"
                        name="city"
                        value={formData.city}
                        onChange={handleChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>


                <div className="col-span-full">
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Shop Location (Google Maps) *
                    </label>
                    <GoogleMapLocationPicker
                        value={formData.shopGoogleLocation}
                        onChange={handleLocationChange}
                        placeholder="Search for your shop or pick on map..."
                        height="400px"
                    />
                </div>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Owner Passport Size Photo *
                    </label>
                    <div className="flex items-center gap-4">
                        <div className="flex-1">
                            <input
                                type="file"
                                name="ownerPassportPhoto"
                                accept="image/*"
                                onChange={handleFileChange}
                                className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                            />
                        </div>
                        <button
                            type="button"
                            className="p-3 bg-theme-input border border-primary-500/20 rounded-xl text-theme-secondary hover:text-primary-500 transition-colors"
                            title="Click Photo"
                        >
                            <Camera className="w-5 h-5" />
                        </button>
                    </div>
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Selfie Photo
                    </label>
                    <div className="flex items-center gap-4">
                        <div className="flex-1">
                            <input
                                type="file"
                                name="selfiePhoto"
                                accept="image/*"
                                onChange={handleFileChange}
                                className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                            />
                        </div>
                        <button
                            type="button"
                            className="p-3 bg-theme-input border border-primary-500/20 rounded-xl text-theme-secondary hover:text-primary-500 transition-colors"
                            title="Take Selfie"
                        >
                            <Camera className="w-5 h-5" />
                        </button>
                    </div>
                </div>
            </div>

            <div className="p-4 rounded-xl bg-theme-input/50 border border-primary-500/10">
                <label className="block text-sm font-medium text-theme-secondary mb-2">
                    Shop Photos (Upload Multiple) *
                </label>
                <input
                    type="file"
                    name="shopPhotos"
                    accept="image/*"
                    multiple
                    onChange={handleFileChange}
                    className="w-full px-4 py-3 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-primary-500/10 file:text-primary-500 hover:file:bg-primary-500/20"
                />
                <p className="text-[11px] text-theme-muted mt-2 px-1">Please select all photos of your shop (interior and exterior) at once.</p>
            </div>

            <div className="grid md:grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Shopact Document
                    </label>
                    <input
                        type="file"
                        name="shopactDocument"
                        accept="image/*,application/pdf"
                        onChange={handleFileChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Udyam Aadhar Document
                    </label>
                    <input
                        type="file"
                        name="udyamAadharDocument"
                        accept="image/*,application/pdf"
                        onChange={handleFileChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        GST Document
                    </label>
                    <input
                        type="file"
                        name="gstDocument"
                        accept="image/*,application/pdf"
                        onChange={handleFileChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        Aadhar Card
                    </label>
                    <input
                        type="file"
                        name="aadharCard"
                        accept="image/*,application/pdf"
                        onChange={handleFileChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>

                <div>
                    <label className="block text-sm font-medium text-theme-secondary mb-1">
                        PAN Card
                    </label>
                    <input
                        type="file"
                        name="panCard"
                        accept="image/*,application/pdf"
                        onChange={handleFileChange}
                        className="w-full px-4 py-2 rounded-xl bg-theme-input border border-primary-500/20 text-theme-primary focus:border-primary-500 focus:outline-none"
                    />
                </div>
            </div>

            <div className="flex gap-3 pt-6">
                <button
                    type="submit"
                    disabled={isSubmitting}
                    className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-green-600 text-white rounded-xl hover:bg-green-700 transition-all font-bold shadow-lg shadow-green-600/20 active:scale-95 disabled:opacity-50"
                >
                    {isSubmitting ? (
                        <>
                            <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                            Submitting...
                        </>
                    ) : (
                        <>
                            <Check className="w-5 h-5" />
                            Submit Registration
                        </>
                    )}
                </button>
                {onClose && (
                    <button
                        type="button"
                        onClick={onClose}
                        className="px-6 py-3 bg-theme-input border border-primary-500/20 text-theme-secondary rounded-xl hover:bg-primary-500/10 transition-colors"
                    >
                        <X className="w-5 h-5" />
                    </button>
                )}
            </div>
        </form>
    );
}
