import { router } from '@inertiajs/react';
import { Badge } from '@ui/components/ui/badge';
import { Button } from '@ui/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@ui/components/ui/card';
import { Textarea } from '@ui/components/ui/textarea';
import { CheckCircle2, XCircle, Clock, AlertCircle } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { useAppText } from '@/lib/app-text';

interface ApprovalSectionProps {
    title: string;
    level: 'cost_control' | 'tax_officer' | 'spv_finance' | 'manager_finance';
    status: 'approved' | 'rejected' | null;
    approvedByName?: string;
    approvedAt: string | null;
    notes?: string;
    canApprove: boolean;
    disabled?: boolean;
    fundRequestId: number;
    requiresTaxAmount?: boolean;
}

export function ApprovalSection({
    title,
    level,
    status,
    approvedByName,
    approvedAt,
    notes: existingNotes,
    canApprove,
    disabled = false,
    fundRequestId,
    requiresTaxAmount = false,
}: ApprovalSectionProps) {
    const [notes, setNotes] = useState('');
    const [taxAmount, setTaxAmount] = useState('');
    const [isSubmitting, setIsSubmitting] = useState(false);
    const { t } = useAppText();

    const handleApprove = (approvalStatus: 'approved' | 'rejected') => {
        setIsSubmitting(true);

        const data: any = {
            status: approvalStatus,
            notes: notes || undefined,
        };

        // Add tax_amount if required (Tax Officer level)
        if (requiresTaxAmount && approvalStatus === 'approved') {
            if (!taxAmount) {
                toast.error(t('fund_request.validation_tax_required'));
                setIsSubmitting(false);

                return;
            }

            data.tax_amount = parseFloat(taxAmount);
        }

        router.post(`/department/finance/fund-request/${fundRequestId}/approve/${level}`, data, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(t('fund_request.approval_success_msg', { action: approvalStatus === 'approved' ? 'menyetujui' : 'menolak' }));
                setNotes('');
                setTaxAmount('');
            },
            onError: (errors) => {
                console.error('Approval errors:', errors);
                toast.error(t('fund_request.approval_error_msg'));
            },
            onFinish: () => setIsSubmitting(false),
        });
    };

    const getStatusBadge = () => {
        if (status === 'approved') {
            return (
                <Badge variant="default" className="bg-green-500">
                    <CheckCircle2 className="mr-1 h-3 w-3" />
                    {t('fund_request.status_approved')}
                </Badge>
            );
        }

        if (status === 'rejected') {
            return (
                <Badge variant="destructive">
                    <XCircle className="mr-1 h-3 w-3" />
                    {t('fund_request.status_rejected')}
                </Badge>
            );
        }

        if (disabled) {
            return (
                <Badge variant="secondary">
                    <AlertCircle className="mr-1 h-3 w-3" />
                    {t('fund_request.status_waiting_prev_approval')}
                </Badge>
            );
        }

        return (
            <Badge variant="outline">
                <Clock className="mr-1 h-3 w-3" />
                Menunggu
            </Badge>
        );
    };

    return (
        <Card className={disabled && status === null ? 'opacity-50' : ''}>
            <CardHeader className="px-4 py-3 md:px-5 md:py-4">
                <div className="flex items-center justify-between">
                    <CardTitle className="text-sm font-semibold md:text-base">{title}</CardTitle>
                    {getStatusBadge()}
                </div>
                {approvedByName && (
                    <CardDescription className="text-xs md:text-sm">
                        {t('fund_request.approval_pic')}: {approvedByName}
                    </CardDescription>
                )}
            </CardHeader>
            <CardContent className="space-y-3 px-4 pb-4 pt-0 md:space-y-4 md:px-5 md:pb-5">
                {/* Show approval form if user can approve */}
                {canApprove && status === null && !disabled && (
                    <div className="space-y-3">
                        {/* Tax Amount input for Tax Officer */}
                        {requiresTaxAmount && (
                            <div className="space-y-1.5">
                                <label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground md:text-sm md:normal-case md:tracking-normal">
                                    {t('fund_request.approval_tax_amount_label')} <span className="text-red-500">*</span>
                                </label>
                                <input
                                    type="number"
                                    step="0.01"
                                    min="0"
                                    placeholder={t('fund_request.approval_tax_amount_placeholder')}
                                    value={taxAmount}
                                    onChange={(e) => setTaxAmount(e.target.value)}
                                    className="flex h-8 w-full rounded-md border border-input bg-background px-2.5 py-1.5 text-xs ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:h-9 md:px-3 md:py-2 md:text-sm"
                                />
                            </div>
                        )}

                        <div className="space-y-1.5">
                            <label className="text-xs font-semibold uppercase tracking-wide text-muted-foreground md:text-sm md:normal-case md:tracking-normal">{t('fund_request.approval_notes_label')}</label>
                            <Textarea
                                placeholder={t('fund_request.approval_notes_placeholder')}
                                value={notes}
                                onChange={(e) => setNotes(e.target.value)}
                                rows={3}
                                className="text-xs md:text-sm"
                            />
                        </div>

                        <div className="flex gap-2">
                            <Button
                                variant="default"
                                onClick={() => handleApprove('approved')}
                                disabled={isSubmitting}
                                className="h-8 flex-1 px-3 text-xs font-semibold md:h-9 md:text-sm"
                            >
                                {isSubmitting ? t('fund_request.approval_processing') : t('fund_request.approval_approve_btn')}
                            </Button>
                            <Button
                                variant="destructive"
                                onClick={() => handleApprove('rejected')}
                                disabled={isSubmitting}
                                className="h-8 flex-1 px-3 text-xs font-semibold md:h-9 md:text-sm"
                            >
                                {isSubmitting ? t('fund_request.approval_processing') : t('fund_request.approval_reject_btn')}
                            </Button>
                        </div>
                    </div>
                )}

                {/* Show status if already approved/rejected */}
                {status !== null && (
                    <div className="space-y-1.5">
                        <div className="text-xs text-muted-foreground md:text-sm">
                            {status === 'approved' ? t('fund_request.status_approved') : t('fund_request.status_rejected')} {t('fund_request.approval_approved_on')}{' '}
                            {approvedAt ? new Date(approvedAt).toLocaleString('id-ID') : '-'}
                        </div>
                        {existingNotes && (
                            <div className="rounded-md bg-muted p-2.5 md:p-3">
                                <p className="mb-1 text-xs font-semibold uppercase tracking-wide text-muted-foreground md:text-sm md:normal-case md:tracking-normal">{t('fund_request.approval_notes_title')}</p>
                                <p className="text-xs text-muted-foreground md:text-sm">{existingNotes}</p>
                            </div>
                        )}
                    </div>
                )}

                {/* Show message if user cannot approve */}
                {!canApprove && status === null && !disabled && (
                    <div className="rounded-md bg-muted p-2.5 md:p-3">
                        <p className="text-xs text-muted-foreground md:text-sm">
                            {t('fund_request.approval_cannot_access')}
                        </p>
                    </div>
                )}

                {/* Show message if disabled (waiting for previous approval) */}
                {disabled && status === null && (
                    <div className="rounded-md bg-muted p-2.5 md:p-3">
                        <p className="text-xs text-muted-foreground md:text-sm">
                            {t('fund_request.approval_waiting_prev')}
                        </p>
                    </div>
                )}
            </CardContent>
        </Card>
    );
}
