import { Head, router } from '@inertiajs/react';
import { Settings } from 'lucide-react';
import { useState } from 'react';
import BucketCard from '@/components/BucketCard';
import InlineEditInput from '@/components/InlineEditInput';
import InlineEditSelect from '@/components/InlineEditSelect';
import SettingsPanel from '@/components/SettingsPanel';
import { csrfToken } from '@/lib/utils';
import { type Bucket, type Scenario } from '@/types';

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 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 [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
    const [editingBucket, setEditingBucket] = useState<Bucket | null>(null);
    const [isSettingsOpen, setIsSettingsOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [formData, setFormData] = useState({ ...defaultFormData });

    const openCreateModal = () => {
        setFormData({ ...defaultFormData });
        setIsCreateModalOpen(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) {
                setEditingBucket(null);
                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) {
                setIsCreateModalOpen(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>

                    {/* Two-column layout */}
                    <div className="grid grid-cols-2 gap-8">
                        {/* Left: Buckets */}
                        <div className="space-y-4">
                            <div className="flex items-center justify-between">
                                <h2 className="text-sm font-mono font-bold tracking-wider uppercase text-red-500/60">
                                    BUCKETS
                                </h2>
                                <button
                                    onClick={openCreateModal}
                                    className="border-2 border-red-500 bg-black px-3 py-1 text-xs font-mono font-bold uppercase tracking-wider text-red-500 hover:bg-red-500 hover:text-black transition-colors"
                                >
                                    + ADD
                                </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="space-y-6 px-4">
                                    {buckets.data.map((bucket) => (
                                        <button
                                            key={bucket.id}
                                            type="button"
                                            onClick={() => setEditingBucket(bucket)}
                                            className="w-full border-4 border-red-500 bg-black glow-red transition-all text-left hover:border-red-400 cursor-pointer"
                                        >
                                            <BucketCard bucket={bucket} />
                                        </button>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* Right: Income */}
                        <div>
                            <div className="flex items-center justify-center border-b border-red-500/40 pb-2 mb-6">
                                <h2 className="text-sm font-mono font-bold tracking-wider uppercase text-red-500/60">
                                    INCOME
                                </h2>
                            </div>
                            <div className="text-center">
                                <input
                                    type="number"
                                    className="w-48 bg-black border-2 border-red-500/50 px-4 py-2 text-center font-digital text-2xl text-red-500 focus:border-red-500 focus:outline-none"
                                    placeholder="0"
                                    min="0"
                                    step="0.01"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            {/* Create Bucket Modal */}
            {isCreateModalOpen && (
                <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={() => {
                                        setIsCreateModalOpen(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>
            )}

            {/* Edit Bucket Modal */}
            {editingBucket && (
                <div
                    className="fixed inset-0 bg-black/80 overflow-y-auto h-full w-full z-50 flex items-start justify-center pt-20"
                    onClick={(e) => { if (e.target === e.currentTarget) setEditingBucket(null); }}
                >
                    <div className="border-4 border-red-500 bg-black p-8 w-96 glow-red">
                        <div className="flex items-center justify-between mb-6">
                            <h3 className="text-lg font-mono font-bold uppercase tracking-wider text-red-500">
                                EDIT BUCKET
                            </h3>
                            <button
                                onClick={() => setEditingBucket(null)}
                                className="text-red-500/60 hover:text-red-500 font-mono text-sm transition-colors"
                            >
                                CLOSE
                            </button>
                        </div>

                        <div className="space-y-4">
                            {/* Name */}
                            <div className="flex items-center justify-between">
                                <span className="text-xs font-mono uppercase text-red-500/60">NAME</span>
                                <InlineEditInput
                                    type="text"
                                    value={editingBucket.name}
                                    onSave={(val) => patchBucket(editingBucket.id, { name: val })}
                                    className="text-red-500 font-mono font-bold"
                                />
                            </div>

                            {/* Type */}
                            <div className="flex items-center justify-between">
                                <span className="text-xs font-mono uppercase text-red-500/60">TYPE</span>
                                <InlineEditSelect
                                    value={editingBucket.type}
                                    options={bucketTypeOptions}
                                    onSave={(val) => patchBucket(editingBucket.id, { type: val })}
                                    displayLabel={editingBucket.type_label}
                                    disabled={editingBucket.type === 'overflow'}
                                    className="text-red-500 font-mono"
                                />
                            </div>

                            {/* Allocation Type */}
                            <div className="flex items-center justify-between">
                                <span className="text-xs font-mono uppercase text-red-500/60">ALLOCATION</span>
                                <InlineEditSelect
                                    value={editingBucket.allocation_type}
                                    options={allocationTypeOptions}
                                    onSave={(val) => patchBucket(editingBucket.id, { allocation_type: val, allocation_value: null })}
                                    displayLabel={editingBucket.allocation_type_label}
                                    disabled={editingBucket.type === 'overflow'}
                                    className="text-red-500 font-mono"
                                />
                            </div>

                            {/* Allocation Value */}
                            {editingBucket.allocation_type !== 'unlimited' && (
                                <div className="flex items-center justify-between">
                                    <span className="text-xs font-mono uppercase text-red-500/60">VALUE</span>
                                    <span className="font-digital text-red-500">
                                        {editingBucket.allocation_type === 'fixed_limit' ? (
                                            <InlineEditInput
                                                value={centsToDollars(editingBucket.allocation_value ?? 0)}
                                                onSave={(val) => patchBucket(editingBucket.id, { allocation_value: dollarsToCents(val) })}
                                                formatDisplay={(v) => `$${v.toFixed(2)}`}
                                                min={0}
                                                step="0.01"
                                            />
                                        ) : (
                                            <InlineEditInput
                                                value={basisPointsToPercent(editingBucket.allocation_value ?? 0)}
                                                onSave={(val) => patchBucket(editingBucket.id, { allocation_value: percentToBasisPoints(val) })}
                                                formatDisplay={(v) => `${v.toFixed(2)}%`}
                                                min={0}
                                                step="0.01"
                                            />
                                        )}
                                    </span>
                                </div>
                            )}

                            {/* Current Balance */}
                            <div className="flex items-center justify-between">
                                <span className="text-xs font-mono uppercase text-red-500/60">CURRENT</span>
                                <InlineEditInput
                                    value={centsToDollars(editingBucket.starting_amount)}
                                    onSave={(val) => patchBucket(editingBucket.id, { starting_amount: dollarsToCents(val) })}
                                    formatDisplay={(v) => `$${v.toFixed(2)}`}
                                    min={0}
                                    step="0.01"
                                    className="font-digital text-red-500"
                                />
                            </div>

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

                            {/* Priority */}
                            <div className="flex items-center justify-between">
                                <span className="text-xs font-mono uppercase text-red-500/60">PRIORITY</span>
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => handlePriorityChange(editingBucket.id, 'up')}
                                        disabled={editingBucket.priority === 1}
                                        className="px-2 py-1 border border-red-500/50 text-red-500 font-mono text-xs hover:bg-red-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                                    >
                                        UP
                                    </button>
                                    <span className="font-digital text-red-500">#{editingBucket.priority}</span>
                                    <button
                                        onClick={() => handlePriorityChange(editingBucket.id, 'down')}
                                        disabled={editingBucket.priority === buckets.data.length}
                                        className="px-2 py-1 border border-red-500/50 text-red-500 font-mono text-xs hover:bg-red-500/20 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
                                    >
                                        DOWN
                                    </button>
                                </div>
                            </div>

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