'use client';
import React, { useState } from 'react';
import { toast } from 'react-toastify';
import { useRouter } from 'next/navigation';
import { FormProvider, useForm } from "react-hook-form";
import { FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import PrimaryButton from "@/components/common-ui/PrimaryButton";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";

interface Props {
    submit: (formData: FormData) => Promise<any>;
}
const formSchema = z.object({
    name: z.string().min(2, { message: "Name must be at least 2 characters" }).max(100, { message: "Name must be at most 100 characters" }),
    address: z.string().min(5, { message: "Address must be at least 5 characters" }).max(200, { message: "Address must be at most 200 characters" }),
    email: z.string().email({ message: "Invalid email address" }),
    password: z.string().min(8, {
        message: "Password must be at least 8 characters"
    }).max(64, {
        message: "Password must be at most 64 characters"
    }),
    password_confirmation: z.string().min(8, {
        message: "Password confirmation must be at least 8 characters"
    }).max(64, {
        message: "Password confirmation must be at most 64 characters"
    }),
    role: z.enum(['admin', 'super admin', 'user'] as const, { message: "Role is required" }),
    permissions: z.array(z.string()).optional(),
    status: z.enum(['active', 'inactive'] as const, { message: "Status is required" }),
}).refine((data) => data.password === data.password_confirmation, {
    message: "Passwords do not match",
});
type FormValues = z.infer<typeof formSchema>;


function UserCreateForm({ submit }: Props) {
    const [loading, setLoading] = useState<boolean>(false);
    const [isSuperAdmin, setIsSuperAdmin] = useState<boolean>(false);
    const plainOptions = [
        'Dashboard',
        'Orders',
        'Products',
        'Product Colors',
        'Product Sizes',
        'Product Styles',
        'Product Accessories',
        'Users Management',
        'Messages',
        'Business Settings',
        'Origins',
        'Business Types',
        'Businesses',
        'General Settings',
        'Web Management',
        'Riders',
        'Reports',
        'Payment Refund',
        'Overseas Production',
        'Self Collection',
    ];
    const router = useRouter();

    const onFinish = async (data: FormValues) => {
        const formData = new FormData();
        if (data.role=== 'super admin') {
            data.permissions = ['super admin'];
        }
        formData.append('name', data.name);
        formData.append('address', data.address);
        formData.append('email', data.email);
        formData.append('password', data.password);
        formData.append('password_confirmation', data.password_confirmation);
        formData.append('role', data.role);
        formData.append('permissions', JSON.stringify(data.permissions));
        formData.append('status', data.status);
        setLoading(true);
        const res = await submit(formData);
        setLoading(false);
        if (res.success) {
            toast.success(res.message);
            router.push('/users');
        } else {
            toast.error(res.message);
            console.log(res.Status);
        }
    };

    const form = useForm<FormValues>({
        resolver: zodResolver(formSchema),
        mode: 'onSubmit',
        defaultValues: {
            name: '',
            address: '',
            email: '',
            password: '',
            password_confirmation: '',
            role: 'admin',
            permissions: [],
            status: 'active',
        },
    });
    
    const handleSuperAdminChange = (value: string) => {
        const normalized = value?.toLowerCase?.() || '';
        setIsSuperAdmin(normalized === 'super admin' || normalized === 'manufacturer');
        // optionally clear permissions when super admin
        if (normalized === 'super admin') {
            form.setValue('permissions', []);
        }
    };

    return (
        <div className='p-4'>
            <FormProvider {...form}>
                <form onSubmit={form.handleSubmit(onFinish)} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 bg-color">
                    <FormField
                        control={form.control}
                        name="name"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Name</FormLabel>
                                <FormControl>
                                    <Input placeholder="Name" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="address"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Address</FormLabel>
                                <FormControl>
                                    <Input placeholder="Address" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="email"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Email</FormLabel>
                                <FormControl>
                                    <Input placeholder="Email" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />

                    <FormField
                        control={form.control}
                        name="password"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Password</FormLabel>
                                <FormControl>
                                    <Input type="password" placeholder="Password" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="password_confirmation"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Confirm Password</FormLabel>
                                <FormControl>
                                    <Input type="password" placeholder="Password" {...field} />
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="role"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Role</FormLabel>
                                <FormControl>
                                    <RadioGroup
                                        defaultValue={field.value || 'user'}
                                        onValueChange={(value) => {
                                            field.onChange(value);
                                            handleSuperAdminChange(value);
                                        }}
                                        className="flex gap-4"
                                    >
                                        <div className="flex items-center gap-2">
                                            <RadioGroupItem value="admin" id="role-admin" />
                                            <label htmlFor="role-admin" className="select-none">Admin</label>
                                        </div>

                                        <div className="flex items-center gap-2">
                                            <RadioGroupItem value="super admin" id="role-super" />
                                            <label htmlFor="role-super" className="select-none">Super Admin</label>
                                        </div>

                                        <div className="flex items-center gap-2">
                                            <RadioGroupItem value="user" id="role-user" />
                                            <label htmlFor="role-user" className="select-none">User</label>
                                        </div>
                                    </RadioGroup>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="status"
                        render={({ field }) => (
                            <FormItem>
                                <FormLabel>Status</FormLabel>
                                <FormControl>
                                    <RadioGroup
                                        defaultValue={field.value || 'active'}
                                        onValueChange={field.onChange}
                                        className="flex gap-4"
                                    >
                                        <div className="flex items-center gap-2">
                                            <RadioGroupItem value="active" id="status-active" />
                                            <label htmlFor="status-active" className="select-none">Active</label>
                                        </div>

                                        <div className="flex items-center gap-2">
                                            <RadioGroupItem value="inactive" id="status-inactive" />
                                            <label htmlFor="status-inactive" className="select-none">Inactive</label>
                                        </div>
                                    </RadioGroup>
                                </FormControl>
                                <FormMessage />
                            </FormItem>
                        )}
                    />
                    <FormField
                        control={form.control}
                        name="permissions"
                        render={({ field }) => (
                            isSuperAdmin ? <></> : (
                                <FormItem className="col-span-1 ">
                                    <FormLabel>Permissions</FormLabel>
                                    <FormControl>
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-1 rounded">
                                            {plainOptions.map((option) => (
                                                <div key={option} className="flex items-center gap-2">
                                                    <input
                                                        type="checkbox"
                                                        value={option}
                                                        checked={field.value?.includes(option) || false}
                                                        onChange={(e) => {
                                                            const newValue = e.target.checked
                                                                ? [...(field.value || []), option]
                                                                : field.value?.filter((val) => val !== option) || [];
                                                            field.onChange(newValue);
                                                        }}
                                                        id={`perm-${option}`}
                                                        className="h-4 w-4"
                                                    />
                                                    <label htmlFor={`perm-${option}`} className="select-none">{option}</label>
                                                </div>
                                            ))}
                                        </div>
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )
                        )}
                    />

                    <div className="col-span-3 flex justify-end">
                        <PrimaryButton
                            loading={loading}
                            text={'Submit'}
                            loadingText={'Submitting...'}
                            type={'submit'}
                        />
                    </div>
                </form>
            </FormProvider>
        </div>

    );
}

export default UserCreateForm;
