import { useForm } from '@inertiajs/react';
import { Loader2, Upload } from 'lucide-react';
import { useRef  } from 'react';
import type {FormEvent} from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';

type ClientDocumentUploadFormProps = {
    constraints: {
        maxFileSizeMb: number;
        acceptedExtensions: string[];
    };
    onSuccess?: () => void;
    renderInCard?: boolean;
};

type UploadFormData = {
    file: File | null;
};

export function ClientDocumentUploadForm({
    constraints,
    onSuccess,
    renderInCard = true,
}: ClientDocumentUploadFormProps) {
    const fileInputRef = useRef<HTMLInputElement | null>(null);
    const { data, setData, post, progress, processing, errors, reset } = useForm<UploadFormData>({
        file: null,
    });

    const submit = (event: FormEvent<HTMLFormElement>) => {
        event.preventDefault();

        post('/client/documents/upload', {
            forceFormData: true,
            preserveScroll: true,
            onSuccess: () => {
                reset('file');

                if (fileInputRef.current) {
                    fileInputRef.current.value = '';
                }

                onSuccess?.();
            },
        });
    };
    const uploadPercentage = progress?.percentage ?? 0;
    const formContent = (
        <form onSubmit={submit} className="space-y-5">
            <div className="grid gap-2">
                <Label htmlFor="client-document-file">Fisier</Label>
                <Input
                    id="client-document-file"
                    ref={fileInputRef}
                    type="file"
                    accept={constraints.acceptedExtensions.map((ext) => `.${ext}`).join(',')}
                    onChange={(event) => setData('file', event.target.files?.[0] ?? null)}
                    disabled={processing}
                />
                <p className="text-xs text-muted-foreground">
                    Formate acceptate: {constraints.acceptedExtensions.join(', ').toUpperCase()}
                </p>
                {errors.file ? <p className="text-sm text-destructive">{errors.file}</p> : null}
            </div>

            {data.file ? (
                <div className="rounded-md border p-3 text-sm">
                    <p className="font-medium">{data.file.name}</p>
                    <p className="text-muted-foreground">
                        {(data.file.size / (1024 * 1024)).toFixed(2)} MB
                    </p>
                </div>
            ) : null}

            {progress ? (
                <div className="space-y-1">
                    <div className="h-2 w-full overflow-hidden rounded bg-muted">
                        <div
                            className="h-full bg-primary transition-all"
                            style={{ width: `${uploadPercentage}%` }}
                        />
                    </div>
                    <p className="text-xs text-muted-foreground">
                        Upload in curs: {Math.round(uploadPercentage)}%
                    </p>
                </div>
            ) : null}

            <Button type="submit" disabled={processing || !data.file}>
                {processing ? (
                    <>
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                        Se incarca...
                    </>
                ) : (
                    <>
                        <Upload className="mr-2 h-4 w-4" />
                        Incarca document
                    </>
                )}
            </Button>
        </form>
    );

    if (!renderInCard) {
        return formContent;
    }

    return (
        <Card>
            <CardHeader>
                <CardTitle>Incarcare document</CardTitle>
                <CardDescription>
                    Incarca un document contabil in format PDF sau imagine. Dimensiune maxima:{' '}
                    {constraints.maxFileSizeMb}MB.
                </CardDescription>
            </CardHeader>
            <CardContent>{formContent}</CardContent>
        </Card>
    );
}
