import { useState } from 'react';
import { Head, usePage, router, Link } from '@inertiajs/react';
import { useTranslation } from 'react-i18next';
import { useDeleteHandler } from '@/hooks/useDeleteHandler';
import { PerPageSelector } from '@/components/ui/per-page-selector';
import { DateRangePicker } from '@/components/ui/date-range-picker';
import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Button } from '@/components/ui/button';
import { Card, CardContent } from "@/components/ui/card";
import { Plus, Trash2, FileText, Eye, Edit } from "lucide-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
import { FilterButton } from '@/components/ui/filter-button';
import { Pagination } from "@/components/ui/pagination";
import { SearchInput } from "@/components/ui/search-input";
import NoRecordsFound from '@/components/no-records-found';
import { formatDate, formatCurrency } from '@/utils/helpers';

interface JournalEntry {
    id: number;
    journal_number: string;
    journal_date: string;
    description: string;
    total_debit: string;
    total_credit: string;
}

interface ManualJournalsIndexProps {
    journals: {
        data: JournalEntry[];
        meta?: any;
        links?: any;
    };
    filters?: {
        search: string;
        date_from: string;
        date_to: string;
    };
    auth: any;
}

export default function Index() {
    const { t } = useTranslation();
    const { journals, filters: initialFilters, auth } = usePage<ManualJournalsIndexProps>().props;
    const urlParams = new URLSearchParams(window.location.search);

    const [filters, setFilters] = useState({
        search: initialFilters?.search || '',
        date_range: (() => {
            const fromDate = urlParams.get('date_from');
            const toDate = urlParams.get('date_to');
            return (fromDate && toDate) ? `${fromDate} - ${toDate}` : '';
        })()
    });

    const [perPage] = useState(urlParams.get('per_page') || '10');
    const [showFilters, setShowFilters] = useState(false);
    
    const { handleDelete } = useDeleteHandler(
        'account.manual-journals.destroy',
        t('Delete Manual Journal'),
        t('Are you sure you want to delete this journal entry?')
    );

    const handleFilterChange = (key: string, value: any) => {
        setFilters(prev => ({ ...prev, [key]: value }));
    };

    const applyFilters = () => {
        let date_from = '';
        let date_to = '';
        if (filters.date_range && filters.date_range.includes(' - ')) {
            const parts = filters.date_range.split(' - ');
            date_from = parts[0];
            date_to = parts[1];
        }

        router.get(route('account.manual-journals.index'), {
            search: filters.search,
            date_from,
            date_to,
            per_page: perPage
        }, { preserveState: true, replace: true });
    };

    const resetFilters = () => {
        setFilters({ search: '', date_range: '' });
        router.get(route('account.manual-journals.index'), { per_page: perPage });
    };

    const breadcrumbs = [
        { label: t('Accounting'), url: route('account.index') },
        { label: t('Manual Journals') }
    ];

    const handlePageChange = (url: string | null) => {
        if (!url) return;
        router.get(url, {}, { preserveState: true, preserveScroll: true });
    };

    return (
        <AuthenticatedLayout
            breadcrumbs={breadcrumbs}
            pageTitle={t('Manage Manual Journals')}
            pageActions={
                auth?.user?.permissions?.includes('manage-account') && (
                    <Button asChild>
                        <Link href={route('account.manual-journals.create')}>
                            <Plus className="mr-2 h-4 w-4" /> {t('Create Journal')}
                        </Link>
                    </Button>
                )
            }
        >
            <div className="space-y-4">
                <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center space-y-4 sm:space-y-0">
                    <div className="flex items-center space-x-2">
                        <PerPageSelector />
                    </div>
                    <div className="flex items-center space-x-2 w-full sm:w-auto">
                        <FilterButton active={showFilters} onClick={() => setShowFilters(!showFilters)} />
                    </div>
                </div>

                {showFilters && (
                    <Card>
                        <CardContent className="pt-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label className="text-sm font-medium mb-1 block">{t('Search')}</label>
                                    <SearchInput
                                        value={filters.search}
                                        onChange={(e) => handleFilterChange('search', e.target.value)}
                                        onSearch={applyFilters}
                                        placeholder={t('Search Journal Number / Description')}
                                    />
                                </div>
                                <div>
                                    <label className="text-sm font-medium mb-1 block">{t('Date Range')}</label>
                                    <DateRangePicker
                                        value={filters.date_range}
                                        onChange={(val) => handleFilterChange('date_range', val)}
                                        placeholder={t('Select Date Range')}
                                    />
                                </div>
                            </div>
                            <div className="mt-4 flex justify-end space-x-2">
                                <Button variant="outline" onClick={resetFilters}>{t('Reset')}</Button>
                                <Button onClick={applyFilters}>{t('Apply')}</Button>
                            </div>
                        </CardContent>
                    </Card>
                )}

                <Card>
                    <CardContent className="p-0">
                        <div className="w-full overflow-auto">
                            <table className="w-full text-sm text-left">
                                <thead className="bg-muted/50 text-muted-foreground border-b">
                                    <tr>
                                        <th className="px-4 py-3 font-medium">{t('Journal Number')}</th>
                                        <th className="px-4 py-3 font-medium">{t('Date')}</th>
                                        <th className="px-4 py-3 font-medium">{t('Description')}</th>
                                        <th className="px-4 py-3 font-medium text-right">{t('Amount')}</th>
                                        <th className="px-4 py-3 font-medium text-right">{t('Action')}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {journals.data.map((journal) => (
                                        <tr key={journal.id} className="border-b last:border-b-0 hover:bg-muted/50">
                                            <td className="px-4 py-3">
                                                <Button variant="link" className="p-0 h-auto font-medium" asChild>
                                                    <Link href={route('account.manual-journals.show', journal.id)}>
                                                        {journal.journal_number}
                                                    </Link>
                                                </Button>
                                            </td>
                                            <td className="px-4 py-3">{formatDate(journal.journal_date)}</td>
                                            <td className="px-4 py-3">{journal.description}</td>
                                            <td className="px-4 py-3 text-right font-medium">
                                                {formatCurrency(journal.total_debit)}
                                            </td>
                                            <td className="px-4 py-3 text-right">
                                                {auth?.user?.permissions?.includes('manage-account') && (
                                                    <div className="flex justify-end gap-1">
                                                        <TooltipProvider>
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <Button
                                                                        variant="ghost"
                                                                        size="icon"
                                                                        className="hover:bg-primary/10 hover:text-primary"
                                                                        asChild
                                                                    >
                                                                        <Link href={route('account.manual-journals.show', journal.id)}>
                                                                            <Eye className="h-4 w-4" />
                                                                        </Link>
                                                                    </Button>
                                                                </TooltipTrigger>
                                                                <TooltipContent>
                                                                    <p>{t('View')}</p>
                                                                </TooltipContent>
                                                            </Tooltip>
                                                        </TooltipProvider>

                                                        <TooltipProvider>
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <Button
                                                                        variant="ghost"
                                                                        size="icon"
                                                                        className="hover:bg-primary/10 hover:text-primary"
                                                                        asChild
                                                                    >
                                                                        <Link href={route('account.manual-journals.edit', journal.id)}>
                                                                            <Edit className="h-4 w-4" />
                                                                        </Link>
                                                                    </Button>
                                                                </TooltipTrigger>
                                                                <TooltipContent>
                                                                    <p>{t('Edit')}</p>
                                                                </TooltipContent>
                                                            </Tooltip>
                                                        </TooltipProvider>

                                                        <TooltipProvider>
                                                            <Tooltip>
                                                                <TooltipTrigger asChild>
                                                                    <Button
                                                                        variant="ghost"
                                                                        size="icon"
                                                                        className="text-destructive hover:text-destructive hover:bg-destructive/10"
                                                                        onClick={() => handleDelete(journal.id)}
                                                                    >
                                                                        <Trash2 className="h-4 w-4" />
                                                                    </Button>
                                                                </TooltipTrigger>
                                                                <TooltipContent>
                                                                    <p>{t('Delete')}</p>
                                                                </TooltipContent>
                                                            </Tooltip>
                                                        </TooltipProvider>
                                                    </div>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>

                        {journals.data.length === 0 && (
                            <NoRecordsFound
                                icon={FileText}
                                title={t('No manual journals found')}
                                description={t('Get started by creating your first manual journal entry.')}
                                hasFilters={!!(filters.search || filters.date_range)}
                                onClearFilters={resetFilters}
                                createPermission="manage-account"
                                onCreateClick={() => router.get(route('account.manual-journals.create'))}
                                createButtonText={t('Create Journal')}
                            />
                        )}
                    </CardContent>

                    {journals.data.length > 0 && (
                        <CardContent className="px-4 py-2 border-t bg-gray-50/30">
                            <Pagination 
                                data={journals as any}
                                routeName="account.manual-journals.index"
                                filters={{ ...filters, per_page: perPage }}
                            />
                        </CardContent>
                    )}
                </Card>
            </div>
        </AuthenticatedLayout>
    );
}
