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

// Step 1 validation schema (config)
const step1Schema = z.object({
    model_name: z.string().min(2, 'Model name must be at least 2 characters'),
    module_name: z.string().min(1, 'Module name is required'),
    app_name: z.string().min(1, 'App name is required'),
    with_statics: z.boolean(),
    with_import: z.boolean(),
    with_export: z.boolean(),
    with_modal: z.boolean(),
});

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

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

interface CrudGeneratorProps {
    app_data: Array<{ id: number; name: string }>;
    modules_data: Array<{ name: string; app: string }>;
    configPrepared?: boolean;
    preparedData?: {
        model_name: string;
        module_name: string;
        app_name: string;
        with_modal: boolean;
        with_statics: boolean;
        with_import: boolean;
        with_export: boolean;
    };
    success?: string;
    error?: string;

    [key: string]: any;
}

export default function CrudGenerator(): ReactNode {
    const {
        app_data,
        modules_data,
        configPrepared: flashConfigPrepared,
        preparedData,
        success,
        error
    } = usePage<CrudGeneratorProps>().props;
    const [currentStep, setCurrentStep] = useState(1);
    const [configPrepared, setConfigPrepared] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [availableModules, setAvailableModules] = useState<Array<{ name: string; app: string }>>([]);

    const {
        register,
        handleSubmit,
        watch,
        setValue,
        reset,
        formState: {errors},
    } = useForm<Step2Data>({
        resolver: zodResolver(step2Schema),
        defaultValues: {
            model_name: '',
            module_name: '',
            app_name: '',
            with_statics: false,
            with_import: false,
            with_export: false,
            with_modal: false,
        },
    });

    const selectedApp = watch('app_name');
    const withStatics = watch('with_statics');
    const withImport = watch('with_import');
    const withExport = watch('with_export');
    const withModal = watch('with_modal');

    // Filter modules based on selected app
    useEffect(() => {
        if (selectedApp) {
            const filtered = modules_data.filter(module => module.app === selectedApp);
            setAvailableModules(filtered);
        } else {
            setAvailableModules([]);
        }
    }, [selectedApp, modules_data]);

    // Handle flash data from backend
    useEffect(() => {
        if (flashConfigPrepared && preparedData) {
            setConfigPrepared(true);
            setCurrentStep(2);
            setValue('model_name', preparedData.model_name);
            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 CRUD generation
        if (success && success.includes('CRUD generated successfully') && currentStep === 2) {
            setTimeout(() => {
                reset();
                setCurrentStep(1);
                setConfigPrepared(false);
            }, 2000);
        }
    }, [flashConfigPrepared, preparedData, error, success, currentStep, setValue, reset]);

    // Handle Step 1: Config preparation
    const handleStep1Submit = async (data: Step1Data) => {
        setIsLoading(true);
        router.post(route('developer.crud.config'), {
            model_name: data.model_name,
            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: CRUD generation
    const handleStep2Submit = async (data: Step2Data) => {
        setIsLoading(true);
        router.post(route('developer.crud.generate'), {
            model_name: data.model_name,
            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);
        }
    };

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

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

    return (
        <>
            <Head title="CRUD Generator"/>
            <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="Crud Generator"
                            description="Generate CRUD operations for your models with customizable 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 CRUD & 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 & Generate
                        </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: CRUD Configuration */}
                            {currentStep === 1 && (
                                <div className="space-y-4 sm:space-y-6">
                                    {/* Basic Configuration */}
                                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6">
                                        <div className="space-y-2">
                                            <Label htmlFor="model_name">Model Name</Label>
                                            <Input
                                                id="model_name"
                                                placeholder="e.g., EmailCategory"
                                                {...register('model_name')}
                                                className={errors.model_name ? 'border-red-500' : ''}
                                            />
                                            {errors.model_name && (
                                                <p className="text-sm text-red-500">{errors.model_name.message}</p>
                                            )}
                                        </div>

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

                                        <div className="space-y-2">
                                            <Label htmlFor="module_name">Module Name</Label>
                                            <Select
                                                onValueChange={(value) => setValue('module_name', value)}
                                                disabled={!selectedApp}
                                            >
                                                <SelectTrigger className={errors.module_name ? 'border-red-500' : ''}>
                                                    <SelectValue placeholder="Select module"/>
                                                </SelectTrigger>
                                                <SelectContent>
                                                    {availableModules.map((module) => (
                                                        <SelectItem key={module.name} value={module.name}>
                                                            {module.name}
                                                        </SelectItem>
                                                    ))}
                                                </SelectContent>
                                            </Select>
                                            {errors.module_name && (
                                                <p className="text-sm text-red-500">{errors.module_name.message}</p>
                                            )}
                                        </div>
                                    </div>

                                    {/* Component Type */}
                                    <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>

                                    {/* Additional Features */}
                                    <div className="space-y-2">
                                        <Label className="text-sm font-medium">Additional Features</Label>
                                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                            <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>

                                    {/* Generated Components Preview */}
                                    <div className="space-y-4">
                                        <Label className="text-base font-medium">Will Generate</Label>
                                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                                            <div className="flex items-center gap-2 p-3 bg-blue-50 rounded-lg">
                                                <Database className="h-5 w-5 text-blue-600"/>
                                                <div>
                                                    <p className="font-medium text-blue-900">Backend Components</p>
                                                    <p className="text-sm text-blue-700">Model, Controller, Request,
                                                        Migration, Resource, Service</p>
                                                </div>
                                            </div>

                                            <div className="flex items-center gap-2 p-3 bg-green-50 rounded-lg">
                                                <Code className="h-5 w-5 text-green-600"/>
                                                <div>
                                                    <p className="font-medium text-green-900">Frontend Components</p>
                                                    <p className="text-sm text-green-700">Index, Create, Edit TSX
                                                        files</p>
                                                </div>
                                            </div>

                                            <div className="flex items-center gap-2 p-3 bg-purple-50 rounded-lg">
                                                <FileText className="h-5 w-5 text-purple-600"/>
                                                <div>
                                                    <p className="font-medium text-purple-900">Routes</p>
                                                    <p className="text-sm text-purple-700">Resource routes in module</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* Step 2: Review & Generate */}
                            {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">Model Name:</span> {watch('model_name')}
                                            </p>
                                            <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
                                            "Generate CRUD" to create the 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' : 'Generate CRUD'}
                                    </Button>
                                </div>
                            </div>
                        </form>
                    </CardContent>
                </Card>
            </div>
        </>
    );
}

CrudGenerator.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            {title: 'Home', href: '/'},
            {title: 'Developer', href: '#'},
            {title: 'Crud Generator', href: '#'},
        ]}
        title="Crud Generator"
    >
        {page}
    </AppLayout>
);
