import AdminLayout from '@admin/layouts/admin/admin-layout';
import { BreadcrumbItem } from '@admin/types';
import { Button } from '@admin/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@admin/components/ui/card';
import { Input } from '@admin/components/ui/input';
import { Textarea } from '@admin/components/ui/textarea';
import { Label } from '@admin/components/ui/label';
import { ReactNode, useEffect, useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import * as z from 'zod';
import { usePage, router } from '@inertiajs/react';
import { Checkbox } from '@admin/components/ui/checkbox';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@admin/components/ui/select';
import { CheckCircle, Circle, ArrowRight, Loader2 } from 'lucide-react';
import { Alert, AlertDescription } from '@admin/components/ui/alert';
import HeadingSmall from '@admin/components/heading-small';

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Dashboard',
        href: route('admin.dashboard.main'),
    },
    {
        title: 'Developer',
        href: '#',
    },
    {
        title: 'Create Modules',
        href: route('admin.developer.modules.create'),
    },
];

// Step 1 validation schema (config) - now includes all features
const step1Schema = z.object({
    module_name: z.string().min(2, { message: 'Module name must be at least 2 characters' }),
    app_name: z.string().min(1, { message: 'Please select an app' }),
    with_modal: z.boolean(),
    with_statics: z.boolean(),
    with_import: z.boolean(),
    with_export: z.boolean(),
});

// Step 2 validation schema (review only)
const step2Schema = z.object({
    module_name: z.string().min(2),
    app_name: z.string().min(1),
    with_modal: z.boolean(),
    with_statics: z.boolean(),
    with_import: z.boolean(),
    with_export: z.boolean(),
});

type Step1Data = z.infer<typeof step1Schema>;
type Step2Data = z.infer<typeof step2Schema>;

function Modules() {
    const { app_data, nameSpace, configPrepared: flashConfigPrepared, preparedData, success, error } = usePage<{
        app_data: any[];
        nameSpace: string;
        configPrepared?: boolean;
        preparedData?: { module_name: string; app_name: string; with_modal: boolean; with_statics: boolean; with_import: boolean; with_export: boolean };
        success?: string;
        error?: string;
    }>().props;
    
    const [currentStep, setCurrentStep] = useState(1);
    const [configPrepared, setConfigPrepared] = useState(false);
    const [isLoading, setIsLoading] = useState(false)
    const {
        register,
        handleSubmit,
        formState: { errors },
        reset,
        setValue,
        watch,
    } = useForm<Step2Data>({
        resolver: zodResolver(step2Schema),
        defaultValues: {
            module_name: '',
            app_name: '',
            with_statics: false,
            with_import: false,
            with_export: false,
            with_modal: false,
        },
    });

    // Handle Step 1: Config preparation with all features
    const handleStep1Submit = async (data: Step1Data) => {
        setIsLoading(true);
        router.post(route('developer.modules.config'), {
            module_name: data.module_name,
            app_name: data.app_name,
            with_modal: data.with_modal,
            with_statics: data.with_statics,
            with_import: data.with_import,
            with_export: data.with_export,
        }, {
            onFinish: () => setIsLoading(false),
        });
    };

    // Handle Step 2: Module creation with features
    const handleStep2Submit = async (data: Step2Data) => {
        setIsLoading(true);
        router.post(route('developer.modules.make'), {
            module_name: data.module_name,
            app_name: data.app_name,
            with_statics: data.with_statics,
            with_import: data.with_import,
            with_export: data.with_export,
            with_modal: data.with_modal,
        }, {
            onFinish: () => setIsLoading(false),
        });
    };

    const onSubmit = async (data: Step2Data) => {
        if (currentStep === 1) {
            handleStep1Submit(data as Step1Data);
        } else {
            handleStep2Submit(data);
        }
    };

    // Watch checkbox values to use in the form
    const withStatics = watch('with_statics');
    const withImport = watch('with_import');
    const withExport = watch('with_export');
    const withModal = watch('with_modal');

    const selectedApp = watch('app_name');

    // Handle flash data from backend
    useEffect(() => {
        console.log('Flash data:', { flashConfigPrepared, preparedData, success, error });
        
        if (flashConfigPrepared && preparedData) {
            console.log('Advancing to Step 2 with data:', preparedData);
            setConfigPrepared(true);
            setCurrentStep(2);
            setValue('module_name', preparedData.module_name);
            setValue('app_name', preparedData.app_name);
            setValue('with_modal', preparedData.with_modal);
            setValue('with_statics', preparedData.with_statics);
            setValue('with_import', preparedData.with_import);
            setValue('with_export', preparedData.with_export);
            setIsLoading(false);
        }
        if (error) {
            setIsLoading(false);
        }
        // Auto-reset to step 1 after successful module creation (not after config preparation)
        if (success && success.includes('Module created successfully') && currentStep === 2) {
            setTimeout(() => {
                reset();
                setCurrentStep(1);
                setConfigPrepared(false);
            }, 2000);
        }
    }, [flashConfigPrepared, preparedData, error, success, currentStep, setValue, reset]);

    const handleBack = () => {
        setCurrentStep(1);
        setConfigPrepared(false);
    };

    const handleReset = () => {
        reset();
        setCurrentStep(1);
        setConfigPrepared(false);
    };
    return (
        <div className="space-y-6 p-4">
            <Card className="rounded-lg border px-5 py-3">
                <div className="flex w-full items-start justify-between">
                    <HeadingSmall
                        title="Create Modules"
                        description="Create a new module with the specified parameters and features"
                    />
                </div>
                <CardContent className="px-0 py-4">
                {/* Step Indicator */}
                <div className="flex items-center gap-4 mt-6">
                    <div className="flex items-center gap-2">
                        {currentStep === 1 ? (
                            <Circle className="h-5 w-5 text-primary fill-primary" />
                        ) : (
                            <CheckCircle className="h-5 w-5 text-green-600" />
                        )}
                        <span className={currentStep === 1 ? 'font-semibold' : 'text-muted-foreground'}>
                            Step 1: Configure Module & Features
                        </span>
                    </div>
                    <ArrowRight className="h-4 w-4 text-muted-foreground" />
                    <div className="flex items-center gap-2">
                        {currentStep === 2 ? (
                            <Circle className="h-5 w-5 text-primary fill-primary" />
                        ) : (
                            <Circle className="h-5 w-5 text-muted-foreground" />
                        )}
                        <span className={currentStep === 2 ? 'font-semibold' : 'text-muted-foreground'}>
                            Step 2: Review & Create
                        </span>
                    </div>
                </div>
                
                {/* Flash Messages */}
                {success && (
                    <Alert className="mt-4 bg-green-50 border-green-200">
                        <AlertDescription className="text-green-800">{success}</AlertDescription>
                    </Alert>
                )}
                {error && (
                    <Alert className="mt-4 bg-red-50 border-red-200">
                        <AlertDescription className="text-red-800">{error}</AlertDescription>
                    </Alert>
                )}

                    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4 sm:space-y-6 mt-6">
                        {/* Step 1: Module Configuration */}
                        {currentStep === 1 && (
                        <div className="space-y-4 sm:space-y-6">
                            {/* Module Name and App Name in same row */}
                            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
                                <div className="space-y-2">
                                    <Label htmlFor="module_name" className="text-sm font-medium">
                                        Module Name *
                                    </Label>
                                    <Input
                                        id="module_name"
                                        placeholder="Enter module name (e.g., UserManagement)"
                                        {...register('module_name')}
                                        className={errors.module_name ? 'border-destructive' : ''}
                                    />
                                    {errors.module_name && (
                                        <p className="text-sm text-destructive">{errors.module_name.message}</p>
                                    )}
                                </div>

                                <div className="space-y-2">
                                    <Label htmlFor="app_name" className="text-sm font-medium">
                                        App Name *
                                    </Label>
                                    <Select onValueChange={(value) => setValue('app_name', value)}>
                                        <SelectTrigger className={errors.app_name ? 'border-destructive' : ''}>
                                            <SelectValue placeholder="Select an app" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            {app_data.map((app: any) => (
                                                <SelectItem key={app.id} value={app.name}>
                                                    {app.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>
                                    {errors.app_name && (
                                        <p className="text-sm text-destructive">{errors.app_name.message}</p>
                                    )}
                                </div>
                            </div>

                            {/* Modal Configuration */}
                            <div className="space-y-2">
                                <Label className="text-sm font-medium">Component Type</Label>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="with_modal"
                                        checked={withModal}
                                        onCheckedChange={(checked) => setValue('with_modal', checked as boolean)}
                                    />
                                    <Label htmlFor="with_modal" className="text-sm font-normal cursor-pointer">
                                        Use Modal Components (Create/Edit as modals)
                                    </Label>
                                </div>
                                <p className="text-xs text-muted-foreground">
                                    When enabled, Create and Edit will be modal components instead of separate pages.
                                </p>
                            </div>

                            {/* Feature Parameters - Checkboxes */}
                            <div className="space-y-2">
                                <Label className="text-sm font-medium">Additional Features</Label>
                                <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="with_statics"
                                            checked={withStatics}
                                            onCheckedChange={(checked) => setValue('with_statics', checked as boolean)}
                                        />
                                        <Label htmlFor="with_statics" className="text-sm font-normal cursor-pointer">
                                            With Statics
                                        </Label>
                                    </div>

                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="with_import"
                                            checked={withImport}
                                            onCheckedChange={(checked) => setValue('with_import', checked as boolean)}
                                        />
                                        <Label htmlFor="with_import" className="text-sm font-normal cursor-pointer">
                                            With Import
                                        </Label>
                                    </div>

                                    <div className="flex items-center space-x-2">
                                        <Checkbox
                                            id="with_export"
                                            checked={withExport}
                                            onCheckedChange={(checked) => setValue('with_export', checked as boolean)}
                                        />
                                        <Label htmlFor="with_export" className="text-sm font-normal cursor-pointer">
                                            With Export
                                        </Label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        )}

                        {/* Step 2: Review & Create */}
                        {currentStep === 2 && (
                        <div className="space-y-4 sm:space-y-6">
                            {/* Review Section */}
                            <div className="bg-muted p-4 rounded-lg space-y-2">
                                <h3 className="font-semibold text-sm">Configuration Review</h3>
                                <div className="text-sm space-y-1">
                                    <p><span className="font-medium">Module Name:</span> {watch('module_name')}</p>
                                    <p><span className="font-medium">App Name:</span> {watch('app_name')}</p>
                                    <p><span className="font-medium">Component Type:</span> {watch('with_modal') ? 'Modal Components' : 'Separate Pages'}</p>
                                    <p><span className="font-medium">With Statics:</span> {watch('with_statics') ? 'Yes' : 'No'}</p>
                                    <p><span className="font-medium">With Import:</span> {watch('with_import') ? 'Yes' : 'No'}</p>
                                    <p><span className="font-medium">With Export:</span> {watch('with_export') ? 'Yes' : 'No'}</p>
                                </div>
                            </div>

                            <div className="text-center py-4">
                                <p className="text-muted-foreground">Review your configuration above and click "Create Module" to generate the module files.</p>
                            </div>
                        </div>
                        )}

                        {/* Action Buttons */}
                        <div className="flex justify-between pt-2">
                            <div>
                                {currentStep === 2 && (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        onClick={handleBack}
                                        disabled={isLoading}
                                    >
                                        Back
                                    </Button>
                                )}
                            </div>
                            <div className="flex space-x-3">
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={handleReset}
                                    disabled={isLoading}
                                >
                                    Reset
                                </Button>
                                <Button
                                    type="submit"
                                    disabled={isLoading}
                                    className="min-w-32"
                                >
                                    {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                                    {currentStep === 1 ? 'Prepare Config' : 'Create Module'}
                                </Button>
                            </div>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </div>
    );
}

Modules.layout = (page: ReactNode) => <AdminLayout breadcrumbs={breadcrumbs}>{page}</AdminLayout>;

export default Modules;
