import { Head, Link, router } from '@inertiajs/react';
import { useState } from 'react';

interface Scenario {
    id: number;
    name: string;
    created_at: string;
    updated_at: string;
}

interface Bucket {
    id: number;
    name: string;
    priority: number;
    sort_order: number;
    allocation_type: string;
    allocation_value: number | null;
    allocation_type_label: string;
    formatted_allocation_value: string;
    current_balance: number;
    has_available_space: boolean;
    available_space: number;
}

interface Props {
    scenario: Scenario;
    buckets: Bucket[];
}

export default function Show({ scenario, buckets }: Props) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [formData, setFormData] = useState({
        name: '',
        allocation_type: 'fixed_limit',
        allocation_value: ''
    });

    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': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '',
                },
                body: JSON.stringify({
                    name: formData.name,
                    allocation_type: formData.allocation_type,
                    allocation_value: formData.allocation_value ? parseFloat(formData.allocation_value) : null
                }),
            });

            if (response.ok) {
                setIsModalOpen(false);
                setFormData({ name: '', allocation_type: 'fixed_limit', allocation_value: '' });
                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);
        }
    };

    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 className="flex items-center justify-between">
                            <div>
                                <Link 
                                    href="/" 
                                    className="text-sm text-blue-600 hover:text-blue-500 mb-2 inline-flex items-center"
                                >
                                    <svg className="mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                                    </svg>
                                    Back to Scenarios
                                </Link>
                                <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>
                    </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={() => setIsModalOpen(true)}
                                className="rounded-md bg-blue-600 px-4 py-2 text-sm font-semibold text-white hover:bg-blue-500"
                            >
                                + Add Bucket
                            </button>
                        </div>
                        
                        <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3">
                            {buckets.map((bucket) => (
                                <div
                                    key={bucket.id}
                                    className="rounded-lg bg-white p-6 shadow transition-shadow hover:shadow-lg border-l-4 border-blue-500"
                                >
                                    <div className="flex items-start justify-between">
                                        <div className="flex-1">
                                            <h3 className="text-lg font-semibold text-gray-900">
                                                {bucket.name}
                                            </h3>
                                            <p className="text-sm text-gray-600 mt-1">
                                                Priority {bucket.priority} • {bucket.allocation_type_label}
                                            </p>
                                        </div>
                                        <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 className="mt-4">
                                        <div className="flex items-center justify-between">
                                            <span className="text-sm text-gray-600">Current Balance</span>
                                            <span className="text-lg font-semibold text-gray-900">
                                                ${bucket.current_balance.toFixed(2)}
                                            </span>
                                        </div>
                                        
                                        <div className="mt-2">
                                            <span className="text-sm text-gray-600">
                                                Allocation: {bucket.formatted_allocation_value}
                                            </span>
                                        </div>
                                        
                                        {bucket.allocation_type === 'fixed_limit' && (
                                            <div className="mt-3">
                                                <div className="flex justify-between text-sm">
                                                    <span>Progress</span>
                                                    <span>
                                                        ${bucket.current_balance.toFixed(2)} / ${Number(bucket.allocation_value)?.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.allocation_value ? Math.min((bucket.current_balance / Number(bucket.allocation_value)) * 100, 100) : 0}%`
                                                        }}
                                                    />
                                                </div>
                                            </div>
                                        )}
                                    </div>
                                    
                                    <div className="mt-4 flex gap-2">
                                        <button className="flex-1 text-sm text-blue-600 hover:text-blue-500">
                                            Edit
                                        </button>
                                        <button className="flex-1 text-sm text-red-600 hover:text-red-500">
                                            Delete
                                        </button>
                                    </div>
                                </div>
                            ))}
                            
                            {/* Virtual Overflow Bucket (placeholder for now) */}
                            <div className="rounded-lg bg-gray-50 p-6 border-2 border-dashed border-gray-300">
                                <div className="text-center">
                                    <div className="mx-auto h-8 w-8 text-gray-400">
                                        <svg fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 100 4m0-4v2m0-6V4" />
                                        </svg>
                                    </div>
                                    <h3 className="mt-2 text-sm font-medium text-gray-500">
                                        Overflow
                                    </h3>
                                    <p className="text-xs text-gray-400 mt-1">
                                        Unallocated funds
                                    </p>
                                    <p className="text-lg font-semibold text-gray-600 mt-2">
                                        $0.00
                                    </p>
                                </div>
                            </div>
                        </div>
                        
                        {/* Placeholder for future features */}
                        <div className="rounded-lg bg-blue-50 p-6 text-center">
                            <h3 className="text-lg font-medium text-blue-900">
                                Coming Next: Streams & Timeline
                            </h3>
                            <p className="text-sm text-blue-700 mt-2">
                                Add income and expense streams, then calculate projections to see your money flow through these buckets over time.
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            {/* Add 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="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>
                                        <option value="unlimited">Unlimited</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>
                                )}

                                <div className="flex gap-3 pt-4">
                                    <button
                                        type="button"
                                        onClick={() => setIsModalOpen(false)}
                                        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>
            )}
        </>
    );
}