import { Head, router } from '@inertiajs/react';
import { Settings } from 'lucide-react';
import { useState } from 'react';
import InlineEditInput from '@/components/InlineEditInput';
import InlineEditSelect from '@/components/InlineEditSelect';
import SettingsPanel from '@/components/SettingsPanel';
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 Props {
    scenario: Scenario;
    buckets: { data: Bucket[] };
}

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

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

const centsToDollars = (cents: number): number => cents / 100;
const dollarsToCents = (dollars: number): number => Math.round(dollars * 100);
const basisPointsToPercent = (bp: number): number => bp / 100;
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 }: Props) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSettingsOpen, setIsSettingsOpen] = 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(`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'] });
            }
        } 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-background p-8">
                <div className="mx-auto max-w-6xl">
                    {/* Header */}
                    <div className="mb-8 flex items-center justify-between border-b border-red-500/40 pb-4">
                        <h1 className="text-2xl font-bold font-mono uppercase tracking-wider text-red-500">
                            BUCKETS
                        </h1>
                        <button
                            onClick={() => setIsSettingsOpen(!isSettingsOpen)}
                            className="p-2 text-red-500/60 hover:text-red-500 transition-colors"
                            title="Settings"
                        >
                            <Settings className="w-5 h-5" />
                        </button>
                    </div>

                    <div
                        className="overflow-hidden transition-all duration-300 ease-in-out"
                        style={{ maxHeight: isSettingsOpen ? '500px' : '0', opacity: isSettingsOpen ? 1 : 0 }}
                    >
                        <SettingsPanel onOpenChange={setIsSettingsOpen} />
                    </div>

                    {/* Buckets */}
                    <div className="space-y-6">
                        <div className="flex items-center justify-end">
                            <button
                                onClick={openCreateModal}
                                className="border-2 border-red-500 bg-black px-4 py-2 text-sm font-mono font-bold uppercase tracking-wider text-red-500 hover:bg-red-500 hover:text-black transition-colors"
                            >
                                + ADD BUCKET
                            </button>
                        </div>

                        {buckets.data.length === 0 ? (
                            <div className="border-4 border-red-500 bg-black p-8 text-center glow-red">
                                <p className="text-red-500 font-mono uppercase tracking-wider mb-4">
                                    NO BUCKETS CONFIGURED
                                </p>
                                <p className="text-red-500/60 font-mono text-sm mb-6">
                                    Income flows through your pipeline into prioritized buckets.
                                </p>
                                <button
                                    onClick={openCreateModal}
                                    className="border-2 border-red-500 bg-black px-6 py-3 font-mono font-bold uppercase tracking-wider text-red-500 hover:bg-red-500 hover:text-black transition-colors"
                                >
                                    CREATE FIRST BUCKET
                                </button>
                            </div>
                        ) : (
                            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                                {buckets.data.map((bucket) => (
                                    <div
                                        key={bucket.id}
                                        className="border-4 border-red-500 bg-black p-6 glow-red transition-all"
                                    >
                                        {/* Header: name + priority */}
                                        <div className="flex items-start justify-between mb-4">
                                            <div className="flex-1">
                                                <h3 className="text-red-500 font-mono font-bold uppercase tracking-wider">
                                                    <InlineEditInput
                                                        type="text"
                                                        value={bucket.name}
                                                        onSave={(val) => patchBucket(bucket.id, { name: val })}
                                                    />
                                                </h3>
                                                <p className="text-red-500/60 text-xs font-mono mt-1 uppercase">
                                                    <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 text-red-500 hover:text-red-300 disabled:opacity-30 disabled:cursor-not-allowed"
                                                    title="Move up"
                                                >
                                                    <svg className="w-3 h-3" 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>
                                                <span className="font-digital text-red-500 text-sm">
                                                    #{bucket.priority}
                                                </span>
                                                <button
                                                    onClick={() => handlePriorityChange(bucket.id, 'down')}
                                                    disabled={bucket.priority === buckets.data.length}
                                                    className="p-1 text-red-500 hover:text-red-300 disabled:opacity-30 disabled:cursor-not-allowed"
                                                    title="Move down"
                                                >
                                                    <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
                                                    </svg>
                                                </button>
                                            </div>
                                        </div>

                                        {/* Filling */}
                                        <div className="flex items-center justify-between mb-2">
                                            <span className="text-red-500/60 text-xs font-mono uppercase">Current</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="font-digital text-red-500"
                                            />
                                        </div>

                                        {/* Allocation */}
                                        <div className="flex items-center justify-between mb-2">
                                            <span className="text-red-500/60 text-xs font-mono uppercase">Allocation</span>
                                            <span className="font-digital text-red-500">
                                                {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>
                                        </div>

                                        {/* Buffer */}
                                        {bucket.allocation_type === 'fixed_limit' && (
                                            <div className="flex items-center justify-between mb-4">
                                                <span className="text-red-500/60 text-xs font-mono uppercase">Buffer</span>
                                                <span className="font-digital text-red-500 text-sm">
                                                    <InlineEditInput
                                                        value={bucket.buffer_multiplier}
                                                        onSave={(val) => patchBucket(bucket.id, { buffer_multiplier: val })}
                                                        formatDisplay={(v) => v > 0 ? `${v}x` : 'NONE'}
                                                        min={0}
                                                        step="0.01"
                                                    />
                                                </span>
                                            </div>
                                        )}

                                        {/* Progress bar placeholder — will be replaced with DigitalProgressBar */}
                                        {bucket.allocation_type === 'fixed_limit' && bucket.effective_capacity !== null && (
                                            <div className="mt-4 border-2 border-red-500/40 p-2">
                                                <div className="flex justify-between text-xs font-mono text-red-500/60 mb-1">
                                                    <span>PROGRESS</span>
                                                    <span className="font-digital text-red-500">
                                                        ${centsToDollars(bucket.current_balance).toFixed(2)} / ${centsToDollars(bucket.effective_capacity).toFixed(2)}
                                                    </span>
                                                </div>
                                                <div className="h-2 bg-red-500/10">
                                                    <div
                                                        className="h-2 bg-red-500 transition-all"
                                                        style={{
                                                            width: `${Math.min((bucket.current_balance / bucket.effective_capacity) * 100, 100)}%`
                                                        }}
                                                    />
                                                </div>
                                            </div>
                                        )}

                                        {/* Delete */}
                                        {bucket.type !== 'overflow' && (
                                            <div className="mt-4 pt-4 border-t border-red-500/20">
                                                <button
                                                    onClick={() => handleDelete(bucket)}
                                                    className="text-red-500/40 text-xs font-mono uppercase hover:text-red-500 transition-colors"
                                                >
                                                    DELETE
                                                </button>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* Create Bucket Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-black/80 overflow-y-auto h-full w-full z-50 flex items-start justify-center pt-20">
                    <div className="border-4 border-red-500 bg-black p-8 w-96 glow-red">
                        <h3 className="text-lg font-mono font-bold uppercase tracking-wider text-red-500 mb-6">
                            ADD BUCKET
                        </h3>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                <label htmlFor="name" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
                                    NAME
                                </label>
                                <input
                                    type="text"
                                    id="name"
                                    value={formData.name}
                                    onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                                    className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
                                    placeholder="e.g., Travel Fund"
                                    required
                                />
                            </div>

                            <div>
                                <label htmlFor="type" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
                                    TYPE
                                </label>
                                <select
                                    id="type"
                                    value={formData.type}
                                    onChange={(e) => setFormData({ ...formData, type: e.target.value as Bucket['type'] })}
                                    className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
                                >
                                    <option value="need">Need</option>
                                    <option value="want">Want</option>
                                </select>
                            </div>

                            <div>
                                <label htmlFor="allocation_type" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
                                    ALLOCATION TYPE
                                </label>
                                <select
                                    id="allocation_type"
                                    value={formData.allocation_type}
                                    onChange={(e) => setFormData({ ...formData, allocation_type: e.target.value })}
                                    className="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
                                >
                                    <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-xs font-mono uppercase text-red-500/60 mb-1">
                                        {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="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono font-digital focus:border-red-500 focus:outline-none"
                                        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_preset" className="block text-xs font-mono uppercase text-red-500/60 mb-1">
                                        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="w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono focus:border-red-500 focus:outline-none"
                                    >
                                        <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 w-full bg-black border-2 border-red-500/50 px-3 py-2 text-red-500 font-mono font-digital focus:border-red-500 focus:outline-none"
                                            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 border-2 border-red-500/50 bg-black px-4 py-2 text-sm font-mono uppercase text-red-500/60 hover:border-red-500 hover:text-red-500 transition-colors"
                                    disabled={isSubmitting}
                                >
                                    CANCEL
                                </button>
                                <button
                                    type="submit"
                                    className="flex-1 border-2 border-red-500 bg-red-500 px-4 py-2 text-sm font-mono font-bold uppercase text-black hover:bg-red-400 transition-colors disabled:opacity-50"
                                    disabled={isSubmitting}
                                >
                                    {isSubmitting ? 'CREATING...' : 'CREATE'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </>
    );
}
