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

export default function OwnerTree({ trees, owners }) {
    const [showModal, setShowModal] = useState(false);
    const [editingTree, setEditingTree] = useState(null);
    const [deleteTree, setDeleteTree] = useState(null);
    const [expandedTree, setExpandedTree] = useState(null);

    const form = useForm({
        name: '',
        owner_ids: [],
    });

    const openCreate = () => {
        setEditingTree(null);
        form.reset();
        form.clearErrors();
        setShowModal(true);
    };

    const openEdit = (tree) => {
        setEditingTree(tree);
        form.setData({
            name: tree.name,
            owner_ids: tree.owners.map(o => o.id),
        });
        form.clearErrors();
        setShowModal(true);
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        if (editingTree) {
            form.put(route('owner-tree.update', editingTree.id), {
                onSuccess: () => setShowModal(false),
            });
        } else {
            form.post(route('owner-tree.store'), {
                onSuccess: () => setShowModal(false),
            });
        }
    };

    const handleDelete = () => {
        router.delete(route('owner-tree.destroy', deleteTree.id), {
            onSuccess: () => setDeleteTree(null),
        });
    };

    const toggleOwner = (ownerId) => {
        const current = form.data.owner_ids;
        if (current.includes(ownerId)) {
            form.setData('owner_ids', current.filter(id => id !== ownerId));
        } else {
            form.setData('owner_ids', [...current, ownerId]);
        }
    };

    // Grand totals
    const grandMonthly = trees.reduce((sum, t) => sum + t.total_monthly, 0);
    const grandYearly = trees.reduce((sum, t) => sum + t.total_yearly, 0);
    const grandPaid = trees.reduce((sum, t) => sum + t.total_paid_to_owners, 0);

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

            <div className="py-12">
                <div className="mx-auto max-w-7xl sm:px-6 lg:px-8 space-y-6">
                    {/* Header */}
                    <div className="bg-white shadow-sm sm:rounded-lg p-6">
                        <div className="flex items-center justify-between">
                            <div>
                                <h3 className="text-lg font-medium text-gray-900">Owner Trees</h3>
                                <p className="mt-1 text-sm text-gray-500">Group owners together and view their combined monthly & yearly income.</p>
                            </div>
                            <div className="flex items-center gap-3">
                                <Link href={route('reports.index')} className="inline-flex items-center rounded-md bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300 transition-colors">
                                    Back to Reports
                                </Link>
                                <button
                                    onClick={openCreate}
                                    className="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors"
                                >
                                    <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" /></svg>
                                    Create Tree
                                </button>
                            </div>
                        </div>
                    </div>

                    {/* Summary Cards */}
                    {trees.length > 0 && (
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div className="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-5 text-white shadow-lg">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-blue-100 text-sm font-medium">Total Monthly Income</p>
                                        <p className="text-2xl font-bold mt-1">{formatCurrency(grandMonthly)}</p>
                                    </div>
                                    <div className="bg-white/20 rounded-lg p-3">
                                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                                    </div>
                                </div>
                            </div>
                            <div className="bg-gradient-to-br from-emerald-500 to-emerald-600 rounded-xl p-5 text-white shadow-lg">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-emerald-100 text-sm font-medium">Total Yearly Income</p>
                                        <p className="text-2xl font-bold mt-1">{formatCurrency(grandYearly)}</p>
                                    </div>
                                    <div className="bg-white/20 rounded-lg p-3">
                                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" /></svg>
                                    </div>
                                </div>
                            </div>
                            <div className="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl p-5 text-white shadow-lg">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-purple-100 text-sm font-medium">Total Paid to Owners</p>
                                        <p className="text-2xl font-bold mt-1">{formatCurrency(grandPaid)}</p>
                                    </div>
                                    <div className="bg-white/20 rounded-lg p-3">
                                        <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 9V7a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2m2 4h10a2 2 0 002-2v-6a2 2 0 00-2-2H9a2 2 0 00-2 2v6a2 2 0 002 2zm7-5a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Tree Cards */}
                    {trees.length === 0 ? (
                        <div className="bg-white shadow-sm sm:rounded-lg p-12 text-center">
                            <div className="mx-auto w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" /></svg>
                            </div>
                            <h3 className="text-lg font-medium text-gray-900 mb-1">No Owner Trees Yet</h3>
                            <p className="text-sm text-gray-500 mb-4">Create your first owner tree to group owners and view combined reports.</p>
                            <button
                                onClick={openCreate}
                                className="inline-flex items-center rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors"
                            >
                                Create First Tree
                            </button>
                        </div>
                    ) : (
                        <div className="space-y-4">
                            {trees.map((tree) => (
                                <div key={tree.id} className="bg-white shadow-sm sm:rounded-lg overflow-hidden">
                                    {/* Tree Header */}
                                    <div
                                        className="p-5 cursor-pointer hover:bg-gray-50 transition-colors"
                                        onClick={() => setExpandedTree(expandedTree === tree.id ? null : tree.id)}
                                    >
                                        <div className="flex items-center justify-between">
                                            <div className="flex items-center gap-3">
                                                <div className="bg-indigo-100 rounded-lg p-2">
                                                    <svg className="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" /></svg>
                                                </div>
                                                <div>
                                                    <h4 className="text-lg font-semibold text-gray-900">{tree.name}</h4>
                                                    <p className="text-sm text-gray-500">{tree.owners.length} owner{tree.owners.length !== 1 ? 's' : ''}</p>
                                                </div>
                                            </div>
                                            <div className="flex items-center gap-6">
                                                <div className="text-right">
                                                    <p className="text-xs text-gray-500 uppercase tracking-wider">Monthly</p>
                                                    <p className="text-lg font-bold text-blue-600">{formatCurrency(tree.total_monthly)}</p>
                                                </div>
                                                <div className="text-right">
                                                    <p className="text-xs text-gray-500 uppercase tracking-wider">Yearly</p>
                                                    <p className="text-lg font-bold text-emerald-600">{formatCurrency(tree.total_yearly)}</p>
                                                </div>
                                                <div className="text-right">
                                                    <p className="text-xs text-gray-500 uppercase tracking-wider">Paid</p>
                                                    <p className="text-lg font-bold text-purple-600">{formatCurrency(tree.total_paid_to_owners)}</p>
                                                </div>
                                                <svg className={`w-5 h-5 text-gray-400 transition-transform ${expandedTree === tree.id ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" /></svg>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Expanded Details */}
                                    {expandedTree === tree.id && (
                                        <div className="border-t border-gray-100">
                                            <div className="p-5">
                                                <div className="flex items-center justify-between mb-3">
                                                    <h5 className="text-sm font-medium text-gray-700">Owners in this tree</h5>
                                                    <div className="flex items-center gap-2">
                                                        <button
                                                            onClick={(e) => { e.stopPropagation(); openEdit(tree); }}
                                                            className="inline-flex items-center gap-1 rounded-md bg-indigo-50 px-3 py-1.5 text-xs font-medium text-indigo-700 hover:bg-indigo-100 transition-colors"
                                                        >
                                                            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
                                                            Edit
                                                        </button>
                                                        <button
                                                            onClick={(e) => { e.stopPropagation(); setDeleteTree(tree); }}
                                                            className="inline-flex items-center gap-1 rounded-md bg-red-50 px-3 py-1.5 text-xs font-medium text-red-700 hover:bg-red-100 transition-colors"
                                                        >
                                                            <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                                            Delete
                                                        </button>
                                                    </div>
                                                </div>
                                                <div className="flex flex-wrap gap-2">
                                                    {tree.owners.map(owner => (
                                                        <span key={owner.id} className="inline-flex items-center gap-1.5 rounded-full bg-gray-100 px-3 py-1.5 text-sm font-medium text-gray-700">
                                                            <span className="w-2 h-2 rounded-full bg-indigo-400"></span>
                                                            {owner.name}
                                                        </span>
                                                    ))}
                                                </div>
                                            </div>
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}

                    {/* Totals Footer */}
                    {trees.length > 0 && (
                        <div className="bg-white shadow-sm sm:rounded-lg p-5">
                            <div className="flex items-center justify-between">
                                <span className="text-sm font-semibold text-gray-700 uppercase tracking-wider">Grand Totals ({trees.length} tree{trees.length !== 1 ? 's' : ''})</span>
                                <div className="flex items-center gap-8">
                                    <div className="text-right">
                                        <p className="text-xs text-gray-500">Monthly</p>
                                        <p className="text-lg font-bold text-blue-600">{formatCurrency(grandMonthly)}</p>
                                    </div>
                                    <div className="text-right">
                                        <p className="text-xs text-gray-500">Yearly</p>
                                        <p className="text-lg font-bold text-emerald-600">{formatCurrency(grandYearly)}</p>
                                    </div>
                                    <div className="text-right">
                                        <p className="text-xs text-gray-500">Paid</p>
                                        <p className="text-lg font-bold text-purple-600">{formatCurrency(grandPaid)}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>

            {/* Create/Edit Modal */}
            <FormModal
                show={showModal}
                onClose={() => setShowModal(false)}
                title={editingTree ? 'Edit Owner Tree' : 'Create Owner Tree'}
            >
                <form onSubmit={handleSubmit} className="space-y-5">
                    {/* Tree Name */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Tree Name</label>
                        <input
                            type="text"
                            value={form.data.name}
                            onChange={e => form.setData('name', e.target.value)}
                            placeholder="e.g. Building A Owners, Family Group"
                            className="w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
                        />
                        {form.errors.name && <p className="mt-1 text-sm text-red-600">{form.errors.name}</p>}
                    </div>

                    {/* Owner Selection */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Select Owners</label>
                        <p className="text-xs text-gray-500 mb-3">Click to add/remove owners from this tree.</p>
                        {form.errors.owner_ids && <p className="mb-2 text-sm text-red-600">{form.errors.owner_ids}</p>}

                        <div className="border rounded-lg max-h-60 overflow-y-auto divide-y divide-gray-100">
                            {owners.map(owner => {
                                const isSelected = form.data.owner_ids.includes(owner.id);
                                return (
                                    <label
                                        key={owner.id}
                                        className={`flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors ${
                                            isSelected ? 'bg-indigo-50' : 'hover:bg-gray-50'
                                        }`}
                                    >
                                        <input
                                            type="checkbox"
                                            checked={isSelected}
                                            onChange={() => toggleOwner(owner.id)}
                                            className="h-4 w-4 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
                                        />
                                        <span className={`text-sm ${isSelected ? 'font-medium text-indigo-900' : 'text-gray-700'}`}>
                                            {owner.name}
                                        </span>
                                    </label>
                                );
                            })}
                        </div>

                        {form.data.owner_ids.length > 0 && (
                            <p className="mt-2 text-xs text-indigo-600 font-medium">
                                {form.data.owner_ids.length} owner{form.data.owner_ids.length !== 1 ? 's' : ''} selected
                            </p>
                        )}
                    </div>

                    {/* Actions */}
                    <div className="flex justify-end gap-3 pt-2 border-t border-gray-100">
                        <button
                            type="button"
                            onClick={() => setShowModal(false)}
                            className="rounded-md bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300 transition-colors"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            disabled={form.processing}
                            className="rounded-md bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 disabled:opacity-50 transition-colors"
                        >
                            {form.processing ? 'Saving...' : editingTree ? 'Update Tree' : 'Create Tree'}
                        </button>
                    </div>
                </form>
            </FormModal>

            {/* Delete Confirmation */}
            <ConfirmDeleteModal
                show={!!deleteTree}
                onClose={() => setDeleteTree(null)}
                onConfirm={handleDelete}
                title="Delete Owner Tree"
                message={`Are you sure you want to delete "${deleteTree?.name}"? This will only remove the grouping, not the owners themselves.`}
            />
        </AuthenticatedLayout>
    );
}
