import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, useForm, router } from '@inertiajs/react';
import { formatCurrency, formatDate } from '@/utils';
import { useState } from 'react';

export default function Report({ expenses, totalIn, totalOut, balance, period, date }) {
    const [currentPeriod, setCurrentPeriod] = useState(period || 'daily');
    const [currentDate, setCurrentDate] = useState(date || new Date().toISOString().split('T')[0]);

    const reload = (newPeriod, newDate) => {
        router.get(route('expenses.report'), { period: newPeriod, date: newDate }, { preserveState: true, replace: true });
    };

    const handlePeriodChange = (p) => {
        setCurrentPeriod(p);
        reload(p, currentDate);
    };

    const handleDateChange = (d) => {
        setCurrentDate(d);
        reload(currentPeriod, d);
    };

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold leading-tight text-gray-800">Cash Book Report</h2>}>
            <Head title="Cash Book Report" />

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8 space-y-6">
                    {/* Controls */}
                    <div className="bg-white shadow-sm sm:rounded-lg p-6">
                        <div className="flex flex-wrap items-center gap-4 justify-between">
                            <div className="flex items-center gap-4">
                                <div className="flex rounded-lg border border-gray-300 overflow-hidden">
                                    <button
                                        onClick={() => handlePeriodChange('daily')}
                                        className={`px-4 py-2 text-sm font-medium ${currentPeriod === 'daily' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'}`}
                                    >
                                        Daily
                                    </button>
                                    <button
                                        onClick={() => handlePeriodChange('weekly')}
                                        className={`px-4 py-2 text-sm font-medium ${currentPeriod === 'weekly' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'}`}
                                    >
                                        Weekly
                                    </button>
                                    <button
                                        onClick={() => handlePeriodChange('monthly')}
                                        className={`px-4 py-2 text-sm font-medium ${currentPeriod === 'monthly' ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-50'}`}
                                    >
                                        Monthly
                                    </button>
                                </div>
                                <input
                                    type="date"
                                    value={currentDate}
                                    onChange={(e) => handleDateChange(e.target.value)}
                                    className="rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                />
                            </div>
                            <a
                                href={route('expenses.report.pdf', { period: currentPeriod, date: currentDate })}
                                className="inline-flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 transition-colors"
                            >
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                                </svg>
                                Download PDF
                            </a>
                        </div>
                    </div>

                    {/* Summary */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                        <div className="bg-white shadow-sm sm:rounded-lg p-6 border-l-4 border-green-500">
                            <p className="text-sm font-medium text-gray-500">Cash In</p>
                            <p className="text-2xl font-bold text-green-700">+ {formatCurrency(totalIn)}</p>
                        </div>
                        <div className="bg-white shadow-sm sm:rounded-lg p-6 border-l-4 border-red-500">
                            <p className="text-sm font-medium text-gray-500">Cash Out</p>
                            <p className="text-2xl font-bold text-red-700">- {formatCurrency(totalOut)}</p>
                        </div>
                        <div className={`bg-white shadow-sm sm:rounded-lg p-6 border-l-4 ${balance >= 0 ? 'border-blue-500' : 'border-red-500'}`}>
                            <p className="text-sm font-medium text-gray-500">Balance</p>
                            <p className={`text-2xl font-bold ${balance >= 0 ? 'text-blue-700' : 'text-red-700'}`}>
                                {balance >= 0 ? '+' : ''} {formatCurrency(balance)}
                            </p>
                        </div>
                    </div>

                    {/* Transactions Table */}
                    <div className="bg-white shadow-sm sm:rounded-lg overflow-hidden">
                        <div className="p-6 text-gray-900">
                            <h3 className="text-lg font-medium mb-4">Transactions</h3>
                            <div className="overflow-x-auto">
                                <table className="min-w-full divide-y divide-gray-200">
                                    <thead className="bg-gray-50">
                                        <tr>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Date</th>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Type</th>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Category</th>
                                            <th className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500">Description</th>
                                            <th className="px-4 py-3 text-right text-xs font-medium uppercase tracking-wider text-gray-500">Amount</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-gray-200 bg-white">
                                        {expenses.map((expense) => (
                                            <tr key={expense.id} className="hover:bg-gray-50">
                                                <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{formatDate(expense.date)}</td>
                                                <td className="whitespace-nowrap px-4 py-4 text-sm">
                                                    <span className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                                                        expense.type === 'cash_in'
                                                            ? 'bg-green-100 text-green-800'
                                                            : 'bg-red-100 text-red-800'
                                                    }`}>
                                                        {expense.type === 'cash_in' ? 'Cash In' : 'Cash Out'}
                                                    </span>
                                                </td>
                                                <td className="whitespace-nowrap px-4 py-4 text-sm text-gray-500">{expense.category?.name || '—'}</td>
                                                <td className="max-w-xs truncate px-4 py-4 text-sm text-gray-900">{expense.description || '—'}</td>
                                                <td className={`whitespace-nowrap px-4 py-4 text-sm text-right font-medium ${expense.type === 'cash_in' ? 'text-green-700' : 'text-red-700'}`}>
                                                    {expense.type === 'cash_in' ? '+' : '-'} {formatCurrency(expense.amount)}
                                                </td>
                                            </tr>
                                        ))}
                                        {expenses.length === 0 && (
                                            <tr>
                                                <td colSpan="5" className="px-4 py-4 text-center text-sm text-gray-500">No transactions found for this period.</td>
                                            </tr>
                                        )}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
