import { Head, router } from '@inertiajs/react';
import { useState } from 'react';
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import InlineEditInput from '@/components/InlineEditInput';
import InlineEditSelect from '@/components/InlineEditSelect';
import IncomeDistributionPreview from '@/components/IncomeDistributionPreview';
import { csrfToken } from '@/lib/utils';
import { type Scenario } from '@/types';

interface Bucket {
    id: string;
    name: string;
    type: 'need' | 'want' | 'overflow';
    type_label: string;
    priority: number;
    sort_order: number;
    allocation_type: string;
    allocation_value: number | null;
    allocation_type_label: string;
    buffer_multiplier: number;
    effective_capacity: number | null;
    starting_amount: number;
    current_balance: number;
    has_available_space: boolean;
    available_space: number | null;
}

interface Stream {
    id: string;
    name: string;
    type: 'income' | 'expense';
    type_label: string;
    amount: number;
    frequency: string;
    frequency_label: string;
    start_date: string;
    end_date: string | null;
    bucket_id: string | null;
    bucket_name: string | null;
    description: string | null;
    is_active: boolean;
    monthly_equivalent: number;
}

interface StreamStats {
    total_streams: number;
    active_streams: number;
    income_streams: number;
    expense_streams: number;
    monthly_income: number;
    monthly_expenses: number;
    monthly_net: number;
}

interface Props {
    scenario: Scenario;
    buckets: { data: Bucket[] };
    streams: { data: Stream[] };
    streamStats?: StreamStats;
}

const bucketTypeBorderColor = {
    need: 'border-blue-500',
    want: 'border-green-500',
    overflow: 'border-amber-500',
} as const;

const bucketTypeOptions = [
    { value: 'need', label: 'Need' },
    { value: 'want', label: 'Want' },
];

const allocationTypeOptions = [
    { value: 'fixed_limit', label: 'Fixed Limit' },
    { value: 'percentage', label: 'Percentage' },
];

/** Convert cents to dollars for display */
const centsToDollars = (cents: number): number => cents / 100;

/** Convert dollars to cents for storage */
const dollarsToCents = (dollars: number): number => Math.round(dollars * 100);

/** Convert basis points to percent for display */
const basisPointsToPercent = (bp: number): number => bp / 100;

/** Convert percent to basis points for storage */
const percentToBasisPoints = (pct: number): number => Math.round(pct * 100);

const formatAllocationValue = (bucket: Bucket): string => {
    if (bucket.allocation_type === 'unlimited') return 'All remaining';
    if (bucket.allocation_value === null) return '--';
    if (bucket.allocation_type === 'percentage') return `${basisPointsToPercent(bucket.allocation_value).toFixed(2)}%`;
    return `$${centsToDollars(bucket.allocation_value).toFixed(2)}`;
};

const patchBucket = async (bucketId: string, data: Record<string, unknown>): Promise<void> => {
    const response = await fetch(`/buckets/${bucketId}`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': csrfToken(),
        },
        body: JSON.stringify(data),
    });

    if (!response.ok) {
        throw new Error('Failed to update bucket');
    }

    router.reload({ only: ['buckets'] });
};

const defaultFormData = {
    name: '',
    type: 'need' as Bucket['type'],
    allocation_type: 'fixed_limit',
    allocation_value: '',
    buffer_multiplier: '0',
    buffer_mode: 'preset' as 'preset' | 'custom',
};

export default function Show({ scenario, buckets, streams = { data: [] }, streamStats }: Props) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [formData, setFormData] = useState({ ...defaultFormData });

    const openCreateModal = () => {
        setFormData({ ...defaultFormData });
        setIsModalOpen(true);
    };

    const handleDelete = async (bucket: Bucket) => {
        if (!confirm(`Are you sure you want to delete "${bucket.name}"?`)) {
            return;
        }

        try {
            const response = await fetch(`/buckets/${bucket.id}`, {
                method: 'DELETE',
                headers: { 'X-CSRF-TOKEN': csrfToken() },
            });

            if (response.ok) {
                router.reload({ only: ['buckets'] });
            } else {
                console.error('Failed to delete bucket');
            }
        } catch (error) {
            console.error('Error deleting bucket:', error);
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setIsSubmitting(true);

        try {
            const response = await fetch(`/scenarios/${scenario.id}/buckets`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': csrfToken(),
                },
                body: JSON.stringify({
                    name: formData.name,
                    type: formData.type,
                    allocation_type: formData.allocation_type,
                    allocation_value: formData.allocation_value
                        ? (formData.allocation_type === 'percentage'
                            ? percentToBasisPoints(parseFloat(formData.allocation_value))
                            : dollarsToCents(parseFloat(formData.allocation_value)))
                        : null,
                    buffer_multiplier: formData.allocation_type === 'fixed_limit' ? parseFloat(formData.buffer_multiplier) || 0 : 0,
                }),
            });

            if (response.ok) {
                setIsModalOpen(false);
                setFormData({ ...defaultFormData });
                router.reload({ only: ['buckets'] });
            } else {
                const errorData = await response.json();
                console.error('Failed to create bucket:', errorData);
            }
        } catch (error) {
            console.error('Error creating bucket:', error);
        } finally {
            setIsSubmitting(false);
        }
    };

    const handlePriorityChange = async (bucketId: string, direction: 'up' | 'down') => {
        const bucket = buckets.data.find(b => b.id === bucketId);
        if (!bucket) return;

        const newPriority = direction === 'up' ? bucket.priority - 1 : bucket.priority + 1;
        if (newPriority < 1 || newPriority > buckets.data.length) return;

        try {
            await patchBucket(bucketId, { priority: newPriority });
        } catch (error) {
            console.error('Error updating bucket priority:', error);
        }
    };

    return (
        <>
            <Head title={scenario.name} />

            <div className="min-h-screen bg-gray-50 py-8">
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    {/* Header */}
                    <div className="mb-8">
                        <div>
                            <h1 className="text-3xl font-bold text-gray-900">{scenario.name}</h1>
                            <p className="mt-2 text-gray-600">
                                Water flows through the pipeline into prioritized buckets
                            </p>
                        </div>
                    </div>

                    {/* Bucket Dashboard */}
                    <div className="space-y-6">
                        <div className="flex items-center justify-between">
                            <h2 className="text-xl font-semibold text-gray-900">Buckets</h2>
                            <button
                                onClick={openCreateModal}
                                className="rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-500"
                            >
                                + Add Bucket
                            </button>
                        </div>

                        {buckets.data.length === 0 ? (
                            <Card className="mx-auto max-w-lg text-center">
                                <CardHeader>
                                    <CardTitle>Set up your buckets</CardTitle>
                                    <CardDescription>
                                        Income flows through your pipeline into prioritized buckets.
                                        Start by creating buckets for your spending categories.
                                    </CardDescription>
                                </CardHeader>
                                <CardContent>
                                    <div className="space-y-3 text-left">
                                        <div className={`rounded-md border-l-4 ${bucketTypeBorderColor.need} bg-blue-50 px-4 py-3`}>
                                            <p className="font-medium text-gray-900">Need</p>
                                            <p className="text-sm text-gray-600">Essential expenses: rent, bills, groceries</p>
                                        </div>
                                        <div className={`rounded-md border-l-4 ${bucketTypeBorderColor.want} bg-green-50 px-4 py-3`}>
                                            <p className="font-medium text-gray-900">Want</p>
                                            <p className="text-sm text-gray-600">Discretionary spending: dining, hobbies, entertainment</p>
                                        </div>
                                        <div className={`rounded-md border-l-4 ${bucketTypeBorderColor.overflow} bg-amber-50 px-4 py-3`}>
                                            <p className="font-medium text-gray-900">Overflow</p>
                                            <p className="text-sm text-gray-600">Catches all remaining funds — one per scenario</p>
                                        </div>
                                    </div>
                                </CardContent>
                                <CardFooter className="justify-center">
                                    <Button onClick={openCreateModal}>
                                        Create Your First Bucket
                                    </Button>
                                </CardFooter>
                            </Card>
                        ) : (
                            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                                {buckets.data.map((bucket) => (
                                    <div
                                        key={bucket.id}
                                        className={`rounded-lg bg-white p-6 shadow transition-shadow hover:shadow-lg border-l-4 ${bucketTypeBorderColor[bucket.type]}`}
                                    >
                                        <div className="flex items-start justify-between">
                                            <div className="flex-1">
                                                <h3 className="text-lg font-semibold text-gray-900">
                                                    <InlineEditInput
                                                        type="text"
                                                        value={bucket.name}
                                                        onSave={(val) => patchBucket(bucket.id, { name: val })}
                                                    />
                                                </h3>
                                                <p className="text-sm text-gray-600 mt-1">
                                                    Priority {bucket.priority} •{' '}
                                                    <InlineEditSelect
                                                        value={bucket.type}
                                                        options={bucketTypeOptions}
                                                        onSave={(val) => patchBucket(bucket.id, { type: val })}
                                                        displayLabel={bucket.type_label}
                                                        disabled={bucket.type === 'overflow'}
                                                    />
                                                    {' '}•{' '}
                                                    <InlineEditSelect
                                                        value={bucket.allocation_type}
                                                        options={allocationTypeOptions}
                                                        onSave={(val) => patchBucket(bucket.id, { allocation_type: val, allocation_value: null })}
                                                        displayLabel={bucket.allocation_type_label}
                                                        disabled={bucket.type === 'overflow'}
                                                    />
                                                </p>
                                            </div>
                                            <div className="flex items-center gap-1">
                                                <button
                                                    onClick={() => handlePriorityChange(bucket.id, 'up')}
                                                    disabled={bucket.priority === 1}
                                                    className="p-1 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                                                    title="Move up in priority"
                                                >
                                                    <svg className="w-3 h-3 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                                    </svg>
                                                </button>
                                                <button
                                                    onClick={() => handlePriorityChange(bucket.id, 'down')}
                                                    disabled={bucket.priority === buckets.data.length}
                                                    className="p-1 rounded hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed"
                                                    title="Move down in priority"
                                                >
                                                    <svg className="w-3 h-3 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                    </svg>
                                                </button>
                                                <span className="rounded-full bg-blue-100 px-2.5 py-0.5 text-xs font-medium text-blue-800">
                                                    #{bucket.priority}
                                                </span>
                                            </div>
                                        </div>

                                        <div className="mt-4">
                                            <div className="flex items-center justify-between">
                                                <span className="text-sm text-gray-600">Current Filling</span>
                                                <InlineEditInput
                                                    value={centsToDollars(bucket.starting_amount)}
                                                    onSave={(val) => patchBucket(bucket.id, { starting_amount: dollarsToCents(val) })}
                                                    formatDisplay={(v) => `$${v.toFixed(2)}`}
                                                    min={0}
                                                    step="0.01"
                                                    className="text-lg font-semibold text-gray-900"
                                                />
                                            </div>

                                            <div className="mt-2">
                                                <span className="text-sm text-gray-600">
                                                    Allocation:{' '}
                                                    {bucket.allocation_type === 'fixed_limit' ? (
                                                        <InlineEditInput
                                                            value={centsToDollars(bucket.allocation_value ?? 0)}
                                                            onSave={(val) => patchBucket(bucket.id, { allocation_value: dollarsToCents(val) })}
                                                            formatDisplay={(v) => `$${v.toFixed(2)}`}
                                                            min={0}
                                                            step="0.01"
                                                        />
                                                    ) : bucket.allocation_type === 'percentage' ? (
                                                        <InlineEditInput
                                                            value={basisPointsToPercent(bucket.allocation_value ?? 0)}
                                                            onSave={(val) => patchBucket(bucket.id, { allocation_value: percentToBasisPoints(val) })}
                                                            formatDisplay={(v) => `${v.toFixed(2)}%`}
                                                            min={0}
                                                            step="0.01"
                                                        />
                                                    ) : (
                                                        formatAllocationValue(bucket)
                                                    )}
                                                </span>
                                                {bucket.allocation_type === 'fixed_limit' && (
                                                    <span className="text-sm text-gray-500 ml-2">
                                                        (
                                                        <InlineEditInput
                                                            value={bucket.buffer_multiplier}
                                                            onSave={(val) => patchBucket(bucket.id, { buffer_multiplier: val })}
                                                            formatDisplay={(v) => v > 0 ? `${v}x buffer` : 'no buffer'}
                                                            min={0}
                                                            step="0.01"
                                                        />
                                                        {bucket.buffer_multiplier > 0 && bucket.effective_capacity !== null && (
                                                            <> = ${centsToDollars(bucket.effective_capacity).toFixed(2)} effective</>
                                                        )}
                                                        )
                                                    </span>
                                                )}
                                            </div>

                                            {bucket.allocation_type === 'fixed_limit' && (
                                                <div className="mt-3">
                                                    <div className="flex justify-between text-sm">
                                                        <span>Progress</span>
                                                        <span>
                                                            ${centsToDollars(bucket.current_balance).toFixed(2)} / ${bucket.effective_capacity !== null ? centsToDollars(bucket.effective_capacity).toFixed(2) : '∞'}
                                                        </span>
                                                    </div>
                                                    <div className="mt-1 h-2 bg-gray-200 rounded-full">
                                                        <div
                                                            className="h-2 bg-blue-600 rounded-full transition-all"
                                                            style={{
                                                                width: `${bucket.effective_capacity ? Math.min((bucket.current_balance / bucket.effective_capacity) * 100, 100) : 0}%`
                                                            }}
                                                        />
                                                    </div>
                                                </div>
                                            )}
                                        </div>

                                        {bucket.type !== 'overflow' && (
                                            <div className="mt-4 flex gap-2">
                                                <button
                                                    onClick={() => handleDelete(bucket)}
                                                    className="flex-1 text-sm text-red-600 hover:text-red-500"
                                                >
                                                    Delete
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )}

                        {/* Income Distribution Preview */}
                        {buckets.data.length > 0 && (
                            <div className="mt-8">
                                <IncomeDistributionPreview scenarioId={scenario.id} />
                            </div>
                        )}

                        {/* Streams Section */}
                        <div className="mt-8">
                            <div className="flex items-center justify-between mb-4">
                                <h2 className="text-xl font-semibold text-gray-900">Income & Expense Streams</h2>
                                <button
                                    className="rounded-md bg-green-600 px-4 py-2 text-sm font-semibold text-white hover:bg-green-500"
                                >
                                    + Add Stream
                                </button>
                            </div>

                            {/* Stream Statistics */}
                            {streamStats && (
                                <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 mb-6">
                                    <div className="bg-white overflow-hidden shadow rounded-lg">
                                        <div className="px-4 py-5 sm:p-6">
                                            <dt className="text-sm font-medium text-gray-500 truncate">
                                                Monthly Income
                                            </dt>
                                            <dd className="mt-1 text-3xl font-semibold text-green-600">
                                                ${streamStats.monthly_income.toFixed(2)}
                                            </dd>
                                        </div>
                                    </div>
                                    <div className="bg-white overflow-hidden shadow rounded-lg">
                                        <div className="px-4 py-5 sm:p-6">
                                            <dt className="text-sm font-medium text-gray-500 truncate">
                                                Monthly Expenses
                                            </dt>
                                            <dd className="mt-1 text-3xl font-semibold text-red-600">
                                                ${streamStats.monthly_expenses.toFixed(2)}
                                            </dd>
                                        </div>
                                    </div>
                                    <div className="bg-white overflow-hidden shadow rounded-lg">
                                        <div className="px-4 py-5 sm:p-6">
                                            <dt className="text-sm font-medium text-gray-500 truncate">
                                                Net Cash Flow
                                            </dt>
                                            <dd className={`mt-1 text-3xl font-semibold ${streamStats.monthly_net >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                                                ${streamStats.monthly_net.toFixed(2)}
                                            </dd>
                                        </div>
                                    </div>
                                    <div className="bg-white overflow-hidden shadow rounded-lg">
                                        <div className="px-4 py-5 sm:p-6">
                                            <dt className="text-sm font-medium text-gray-500 truncate">
                                                Active Streams
                                            </dt>
                                            <dd className="mt-1 text-3xl font-semibold text-gray-900">
                                                {streamStats.active_streams} / {streamStats.total_streams}
                                            </dd>
                                        </div>
                                    </div>
                                </div>
                            )}

                            {streams.data.length === 0 ? (
                                <div className="rounded-lg bg-white p-8 text-center shadow">
                                    <p className="text-gray-600">No streams yet. Add income or expense streams to start tracking cash flow.</p>
                                </div>
                            ) : (
                                <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
                                    <table className="min-w-full divide-y divide-gray-300">
                                        <thead className="bg-gray-50">
                                            <tr>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Name
                                                </th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Type
                                                </th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Amount
                                                </th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Frequency
                                                </th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Bucket
                                                </th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Start Date
                                                </th>
                                                <th className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">
                                                    Status
                                                </th>
                                                <th className="relative px-6 py-3">
                                                    <span className="sr-only">Actions</span>
                                                </th>
                                            </tr>
                                        </thead>
                                        <tbody className="divide-y divide-gray-200 bg-white">
                                            {streams.data.map((stream) => (
                                                <tr key={stream.id}>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm font-medium text-gray-900">
                                                        {stream.name}
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                        <span className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${
                                                            stream.type === 'income'
                                                                ? 'bg-green-100 text-green-800'
                                                                : 'bg-red-100 text-red-800'
                                                        }`}>
                                                            {stream.type_label}
                                                        </span>
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                        ${stream.amount.toFixed(2)}
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                        {stream.frequency_label}
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                        {stream.bucket_name || '-'}
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                        {new Date(stream.start_date).toLocaleDateString()}
                                                    </td>
                                                    <td className="whitespace-nowrap px-6 py-4 text-sm text-gray-500">
                                                        <button
                                                            className={`inline-flex rounded-full px-2 text-xs font-semibold leading-5 ${
                                                                stream.is_active
                                                                    ? 'bg-green-100 text-green-800'
                                                                    : 'bg-gray-100 text-gray-800'
                                                            }`}
                                                        >
                                                            {stream.is_active ? 'Active' : 'Inactive'}
                                                        </button>
                                                    </td>
                                                    <td className="relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-6">
                                                        <button className="text-indigo-600 hover:text-indigo-900 mr-3">
                                                            Edit
                                                        </button>
                                                        <button className="text-red-600 hover:text-red-900">
                                                            Delete
                                                        </button>
                                                    </td>
                                                </tr>
                                            ))}
                                        </tbody>
                                    </table>
                                </div>
                            )}
                        </div>

                    </div>
                </div>
            </div>

            {/* Create Bucket Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
                    <div className="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
                        <div className="mt-3">
                            <h3 className="text-lg font-medium text-gray-900 mb-4">Add New Bucket</h3>
                            <form onSubmit={handleSubmit} className="space-y-4">
                                <div>
                                    <label htmlFor="name" className="block text-sm font-medium text-gray-700">
                                        Bucket Name
                                    </label>
                                    <input
                                        type="text"
                                        id="name"
                                        value={formData.name}
                                        onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                                        placeholder="e.g., Travel Fund"
                                        required
                                    />
                                </div>

                                <div>
                                    <label htmlFor="type" className="block text-sm font-medium text-gray-700">
                                        Bucket Type
                                    </label>
                                    <select
                                        id="type"
                                        value={formData.type}
                                        onChange={(e) => setFormData({ ...formData, type: e.target.value as Bucket['type'] })}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                                    >
                                        <option value="need">Need</option>
                                        <option value="want">Want</option>
                                    </select>
                                </div>

                                <div>
                                    <label htmlFor="allocation_type" className="block text-sm font-medium text-gray-700">
                                        Allocation Type
                                    </label>
                                    <select
                                        id="allocation_type"
                                        value={formData.allocation_type}
                                        onChange={(e) => setFormData({ ...formData, allocation_type: e.target.value })}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                                    >
                                        <option value="fixed_limit">Fixed Limit</option>
                                        <option value="percentage">Percentage</option>
                                    </select>
                                </div>

                                {formData.allocation_type !== 'unlimited' && (
                                    <div>
                                        <label htmlFor="allocation_value" className="block text-sm font-medium text-gray-700">
                                            {formData.allocation_type === 'percentage' ? 'Percentage (%)' : 'Amount ($)'}
                                        </label>
                                        <input
                                            type="number"
                                            id="allocation_value"
                                            value={formData.allocation_value}
                                            onChange={(e) => setFormData({ ...formData, allocation_value: e.target.value })}
                                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                                            placeholder={formData.allocation_type === 'percentage' ? '25' : '1000'}
                                            step={formData.allocation_type === 'percentage' ? '0.01' : '0.01'}
                                            min={formData.allocation_type === 'percentage' ? '0.01' : '0'}
                                            max={formData.allocation_type === 'percentage' ? '100' : undefined}
                                            required
                                        />
                                    </div>
                                )}

                                {formData.allocation_type === 'fixed_limit' && (
                                    <div>
                                        <label htmlFor="buffer_multiplier" className="block text-sm font-medium text-gray-700">
                                            Buffer
                                        </label>
                                        <select
                                            id="buffer_preset"
                                            value={formData.buffer_mode === 'custom' ? 'custom' : formData.buffer_multiplier}
                                            onChange={(e) => {
                                                if (e.target.value === 'custom') {
                                                    setFormData({ ...formData, buffer_mode: 'custom' });
                                                } else {
                                                    setFormData({ ...formData, buffer_multiplier: e.target.value, buffer_mode: 'preset' });
                                                }
                                            }}
                                            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                                        >
                                            <option value="0">None</option>
                                            <option value="0.5">0.5x (50% extra)</option>
                                            <option value="1">1x (100% extra)</option>
                                            <option value="1.5">1.5x (150% extra)</option>
                                            <option value="2">2x (200% extra)</option>
                                            <option value="custom">Custom</option>
                                        </select>
                                        {formData.buffer_mode === 'custom' && (
                                            <input
                                                type="number"
                                                id="buffer_multiplier"
                                                value={formData.buffer_multiplier}
                                                onChange={(e) => setFormData({ ...formData, buffer_multiplier: e.target.value })}
                                                className="mt-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-gray-900"
                                                placeholder="e.g., 0.75"
                                                step="0.01"
                                                min="0"
                                            />
                                        )}
                                    </div>
                                )}

                                <div className="flex gap-3 pt-4">
                                    <button
                                        type="button"
                                        onClick={() => {
                                            setIsModalOpen(false);
                                            setFormData({ ...defaultFormData });
                                        }}
                                        className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-200 rounded-md hover:bg-gray-300"
                                        disabled={isSubmitting}
                                    >
                                        Cancel
                                    </button>
                                    <button
                                        type="submit"
                                        className="flex-1 px-4 py-2 text-sm font-medium text-white bg-blue-600 rounded-md hover:bg-blue-700 disabled:opacity-50"
                                        disabled={isSubmitting}
                                    >
                                        {isSubmitting ? 'Creating...' : 'Create Bucket'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            )}
        </>
    );
}
