import { Head, router } from '@inertiajs/react';
import { useState } from 'react';
import { toast } from 'sonner';
import { FinanceAppLayout } from '@/layouts/finance-app-layout';
import { useAppText } from '@/lib/app-text';
import type { User } from '@/types';
import type { FundRequestFormData, Company, Bank, Budget, Branch, Department } from '@/types/fund-request';
import { FundRequestForm } from './components/FundRequestForm';

interface CreateFundRequestPageProps {
    title: string;
    companies: Company[];
    branches: Branch[];
    departments: Department[];
    employees: User[];
    banks: Bank[];
    budgets: Budget[];
    isServiceMode?: boolean;
}



export default function CreateFundRequest({ title, companies, branches, departments, employees, banks, budgets, isServiceMode = false }: CreateFundRequestPageProps) {
    const { t: text } = useAppText();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const basePath = isServiceMode ? '/service/fund-request' : '/department/finance/fund-request';

    const showSubmitError = (errors?: Record<string, string | string[]>) => {
        if (!errors) {
 toast.error(text('common.msg_error'));

 return; 
}

        for (const value of Object.values(errors)) {
            const msg = Array.isArray(value) ? value[0] : value;

            if (msg) {
 toast.error(msg);

 return; 
}
        }

        toast.error(text('common.msg_error'));
    };

    const handleSubmit = (data: FundRequestFormData) => {
        router.post(
            basePath,
            data as any,
            {
                preserveScroll: true,
                forceFormData: true,
                onStart: () => setIsSubmitting(true),
                onSuccess: () => {
                    toast.success(text('common.msg_success_create', { module: text('fund_request.title') }));
                    router.visit(basePath);
                },
                onError: (errors) => {
                    showSubmitError(errors as Record<string, string | string[]>);
                },
                onFinish: () => setIsSubmitting(false),
            }
        );
    };

    const pageContent = (
        <div className="flex h-full flex-1 flex-col gap-4 p-4">
            <div className="flex items-center justify-between">
                <div>
                    <h1 className="text-2xl font-bold tracking-tight">{text('fund_request.create_title')}</h1>
                    <p className="text-muted-foreground">
                        {text('fund_request.create_description')}
                    </p>
                </div>
            </div>

            <div className="overflow-hidden rounded-lg border border-border bg-card text-card-foreground shadow-sm">
                <div className="p-6">
                    <FundRequestForm
                        onSubmit={handleSubmit}
                        onCancel={() => router.visit(basePath)}
                        isSubmitting={isSubmitting}
                        companies={companies}
                        branches={branches}
                        departments={departments}
                        employees={employees}
                        banks={banks}
                        budgets={budgets}
                    />
                </div>
            </div>
        </div>
    );

    return (
        <>
            <Head title={title || text('fund_request.create_title')} />
            {isServiceMode ? (
                <div className="min-h-screen bg-background">
                    <div className="mx-auto max-w-5xl px-4 py-6 sm:px-6 lg:px-8">
                        {pageContent}
                    </div>
                </div>
            ) : (
                <FinanceAppLayout>
                    {pageContent}
                </FinanceAppLayout>
            )}
        </>
    );
}

