import { useState } from 'react';
import { Head, useForm, Link } from '@inertiajs/react';
import { useTranslation } from 'react-i18next';
import AuthenticatedLayout from "@/layouts/authenticated-layout";
import { Button } from '@/components/ui/button';
import { Card, CardContent } from "@/components/ui/card";
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, Trash2, Save, ArrowLeft } from "lucide-react";
import { formatCurrency } from '@/utils/helpers';

interface ChartOfAccount {
    id: number;
    account_code: string;
    account_name: string;
}

interface ManualJournalsCreateProps {
    chartOfAccounts: ChartOfAccount[];
    auth: any;
}

export default function Create({ chartOfAccounts, auth }: ManualJournalsCreateProps) {
    const { t } = useTranslation();

    const { data, setData, post, processing, errors } = useForm({
        journal_date: new Date().toISOString().split('T')[0],
        description: '',
        items: [
            { account_id: '', debit: '', credit: '' },
            { account_id: '', debit: '', credit: '' }
        ]
    });

    const addItem = () => {
        setData('items', [...data.items, { account_id: '', debit: '', credit: '' }]);
    };

    const removeItem = (index: number) => {
        const newItems = [...data.items];
        newItems.splice(index, 1);
        setData('items', newItems);
    };

    const handleItemChange = (index: number, field: string, value: string) => {
        const newItems = [...data.items];
        (newItems as any)[index][field] = value;
        setData('items', newItems);
    };

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        post(route('account.manual-journals.store'));
    };

    const totalDebit = data.items.reduce((sum, item) => sum + (parseFloat(item.debit) || 0), 0);
    const totalCredit = data.items.reduce((sum, item) => sum + (parseFloat(item.credit) || 0), 0);
    const isBalanced = Math.abs(totalDebit - totalCredit) < 0.01;

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

    return (
        <AuthenticatedLayout
            breadcrumbs={breadcrumbs}
            pageTitle={t('Create Manual Journal')}
            backUrl={route('account.manual-journals.index')}
        >
            <form onSubmit={submit}>
                <Card className="mb-6">
                    <CardContent className="p-6">
                        <div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                            <div>
                                <Label htmlFor="journal_date">{t('Date')} <span className="text-red-500">*</span></Label>
                                <Input
                                    id="journal_date"
                                    type="date"
                                    value={data.journal_date}
                                    onChange={e => setData('journal_date', e.target.value)}
                                    className="mt-1"
                                    required
                                />
                                {errors.journal_date && <p className="text-red-500 text-sm mt-1">{errors.journal_date}</p>}
                            </div>
                            
                            <div>
                                <Label htmlFor="description">{t('Description')} <span className="text-red-500">*</span></Label>
                                <Textarea
                                    id="description"
                                    value={data.description}
                                    onChange={e => setData('description', e.target.value)}
                                    placeholder={t('Enter description for this journal entry')}
                                    className="mt-1"
                                    rows={1}
                                    required
                                />
                                {errors.description && <p className="text-red-500 text-sm mt-1">{errors.description}</p>}
                            </div>
                        </div>

                        <div className="border rounded-md overflow-hidden mb-4">
                            <table className="w-full text-sm text-left">
                                <thead className="bg-muted text-muted-foreground">
                                    <tr>
                                        <th className="px-4 py-3 w-1/2">{t('Account')}</th>
                                        <th className="px-4 py-3 w-1/5">{t('Debit')}</th>
                                        <th className="px-4 py-3 w-1/5">{t('Credit')}</th>
                                        <th className="px-4 py-3 w-10 text-center"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {data.items.map((item, index) => (
                                        <tr key={index} className="border-t">
                                            <td className="px-4 py-2">
                                                <Select
                                                    value={item.account_id}
                                                    onValueChange={(val) => handleItemChange(index, 'account_id', val)}
                                                >
                                                    <SelectTrigger>
                                                        <SelectValue placeholder={t('Select Account')} />
                                                    </SelectTrigger>
                                                    <SelectContent searchable>
                                                        {chartOfAccounts.map((acc) => (
                                                            <SelectItem key={acc.id} value={acc.id.toString()}>
                                                                {acc.account_code} - {acc.account_name}
                                                            </SelectItem>
                                                        ))}
                                                    </SelectContent>
                                                </Select>
                                            </td>
                                            <td className="px-4 py-2">
                                                <Input
                                                    type="number"
                                                    min="0"
                                                    step="0.01"
                                                    value={item.debit}
                                                    onChange={(e) => handleItemChange(index, 'debit', e.target.value)}
                                                    placeholder="0.00"
                                                    disabled={!!item.credit && parseFloat(item.credit) > 0}
                                                />
                                            </td>
                                            <td className="px-4 py-2">
                                                <Input
                                                    type="number"
                                                    min="0"
                                                    step="0.01"
                                                    value={item.credit}
                                                    onChange={(e) => handleItemChange(index, 'credit', e.target.value)}
                                                    placeholder="0.00"
                                                    disabled={!!item.debit && parseFloat(item.debit) > 0}
                                                />
                                            </td>
                                            <td className="px-4 py-2 text-center">
                                                {data.items.length > 2 && (
                                                    <Button
                                                        type="button"
                                                        variant="ghost"
                                                        size="icon"
                                                        className="text-destructive h-8 w-8"
                                                        onClick={() => removeItem(index)}
                                                    >
                                                        <Trash2 className="h-4 w-4" />
                                                    </Button>
                                                )}
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                                <tfoot className="bg-muted/50 border-t">
                                    <tr>
                                        <td className="px-4 py-3 font-medium text-right">
                                            {t('Total')}:
                                        </td>
                                        <td className="px-4 py-3 font-bold text-lg">
                                            {formatCurrency(totalDebit)}
                                        </td>
                                        <td className="px-4 py-3 font-bold text-lg">
                                            {formatCurrency(totalCredit)}
                                        </td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        {!isBalanced && totalDebit > 0 && totalCredit > 0 && (
                            <div className="text-red-500 text-sm mb-4 font-medium flex items-center bg-red-50 p-3 rounded-md border border-red-200">
                                {t('Warning: Debits and Credits must be equal. Difference: ')} {formatCurrency(Math.abs(totalDebit - totalCredit))}
                            </div>
                        )}

                        <div className="flex justify-between items-center mt-6">
                            <Button type="button" variant="outline" onClick={addItem}>
                                <Plus className="w-4 h-4 mr-2" /> {t('Add Row')}
                            </Button>
                            
                            <div className="flex space-x-2">
                                <Button variant="outline" type="button" asChild>
                                    <Link href={route('account.manual-journals.index')}>
                                        {t('Cancel')}
                                    </Link>
                                </Button>
                                <Button 
                                    type="submit" 
                                    disabled={processing || !isBalanced || totalDebit === 0}
                                >
                                    <Save className="w-4 h-4 mr-2" />
                                    {t('Save Journal Entry')}
                                </Button>
                            </div>
                        </div>
                    </CardContent>
                </Card>
            </form>
        </AuthenticatedLayout>
    );
}
