import Form from '@/components/form/Form';
import FormField from '@/components/form/FormField';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import { yupResolver } from '@hookform/resolvers/yup';
import { Head, router, usePage } from '@inertiajs/react';
import { ArrowLeft, Calendar, Plus } from 'lucide-react';
import { useMemo } from 'react';
import { useFormContext, useWatch } from 'react-hook-form';
import * as yup from 'yup';

declare const route: (...args: any[]) => string;

interface StatusOption {
    label: string;
    value: number;
}

interface PageProps extends Record<string, unknown> {
    statuses: StatusOption[];
}

const schema = yup.object({
    name: yup.string().required('Plan name is required').max(255, 'Plan name must not exceed 255 characters'),
    customer_group: yup.array().of(yup.string().max(100)).nullable(),
    discount_type: yup.string().required('Discount type is required').oneOf(['percentage', 'fixed'], 'Invalid discount type'),
    discount_value: yup.number().typeError('Discount value is required').required('Discount value is required').min(0),
    priority: yup.number().typeError('Priority must be a number').required('Priority is required').min(0),
    start_date: yup.string().nullable(),
    end_date: yup
        .string()
        .nullable()
        .test('after-start', 'End Date / Time must be after Start Date / Time', function (value) {
            if (!value) return true;
            const start = this.parent.start_date;
            if (!start) return true;
            return new Date(value) >= new Date(start);
        }),
    status: yup.number().required('Status is required'),
});

const customerGroupOptions = [
    { label: 'VIP', value: 'VIP' },
    { label: 'Loyalty', value: 'Loyalty' },
    { label: 'Wholesale', value: 'Wholesale' },
    { label: 'Retail', value: 'Retail' },
];

export default function Create() {
    const { statuses } = usePage<PageProps>().props;

    const defaultValues = useMemo(
        () => ({
            name: '',
            customer_group: [] as string[],
            discount_type: 'percentage',
            discount_value: 0,
            priority: 0,
            start_date: '',
            end_date: '',
            status: 1,
        }),
        [],
    );

    const handleSubmit = (formData: any) => {
        router.post(route('discount.store'), formData);
    };

    return (
        <>
            <Head title="Create Discount Plan" />
            <div className="mx-auto flex w-full flex-1 flex-col gap-4 p-3 sm:gap-6 sm:p-2">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-xl font-bold tracking-tight sm:text-2xl">Create Discount Plan</h1>
                        <p className="text-sm text-gray-600">Define the scope of your promotion to target the right audience.</p>
                    </div>
                    <Button className="gap-2" type="button" onClick={() => history.back()}>
                        <ArrowLeft className="h-4 w-4" />
                        Back
                    </Button>
                </div>

                <Form resolver={yupResolver(schema)} defaultValues={defaultValues} submitHandler={handleSubmit} formClassNames="space-y-6">
                    <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
                        <div className="space-y-4 lg:col-span-2">
                            <Card className="p-4">
                                <h2 className="mb-4 text-lg font-semibold">Discount Plan Information</h2>
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
                                    <div className="md:col-span-1">
                                        <FormField type="text" name="name" label="Plan Name" placeholder="e.g. Wholesale 10% All Orders" required />
                                    </div>
                                    <div className="md:col-span-1">
                                        <FormField
                                            type="multiselect"
                                            name="customer_group"
                                            label="Customer Group"
                                            placeholder="Select or add groups"
                                            searchable
                                            allowCustomOptions
                                            options={customerGroupOptions}
                                        />
                                    </div>
                                </div>
                            </Card>

                            <Card className="p-4">
                                <h2 className="mb-4 text-lg font-semibold">Discount setup</h2>
                                <p className="mb-4 text-sm text-gray-500">Define when the offer activates.</p>
                                <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
                                    <FormField
                                        type="select"
                                        name="discount_type"
                                        label="Discount Type"
                                        required
                                        options={[
                                            { label: 'Percentage', value: 'percentage' },
                                            { label: 'Fixed', value: 'fixed' },
                                        ]}
                                    />
                                    <FormField type="number" name="discount_value" label="Discount Value" required />
                                    <FormField type="number" name="priority" label="Priority" required />
                                </div>
                            </Card>
                        </div>

                        <div className="space-y-4 lg:col-span-1">
                            <Card className="p-4">
                                <h2 className="mb-4 text-lg font-semibold">Overview</h2>
                                <FormField
                                    type="select"
                                    name="status"
                                    label="Select Status"
                                    required
                                    options={(statuses || []).map((status) => ({ label: status.label, value: status.value }))}
                                />
                            </Card>

                            <Card className="p-4">
                                <h2 className="mb-4 text-lg font-semibold">Scheduling</h2>
                                <div className="space-y-4">
                                    <div>
                                        <FormField type="datepicker" name="start_date" label="Start Date" placeholder="Select start date" />
                                    </div>
                                    <div>
                                        <FormField type="datepicker" name="end_date" label="End Date" placeholder="Select end date" />
                                    </div>
                                </div>
                            </Card>
                        </div>
                    </div>

                    <div className="flex justify-end gap-3">
                        <Button type="button" variant="outline" onClick={() => history.back()}>
                            Cancel
                        </Button>
                        <Button type="submit">
                            <Plus className="h-4 w-4" />
                            Create Discount Plan
                        </Button>
                    </div>
                </Form>
            </div>
        </>
    );
}

Create.layout = (page: React.ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Dashboard', href: route('dashboard') },
            { title: 'Discount', href: route('discount.index') },
            { title: 'Create', href: route('discount.create') },
        ]}
        title="Create Discount Plan"
    >
        {page}
    </AppLayout>
);
