import { useState } from "react";
import { useTranslation } from "react-i18next";
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from "@/components/ui/card";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import { Button } from "@/components/ui/button";
import { Download, Loader2, FileJson } from "lucide-react";
import { apiRequest } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";


import { User } from "@shared/schema";

interface DataExportCardProps {
    user: User | undefined | null;
}

export function DataExportCard({ user }: DataExportCardProps) {
    const { t } = useTranslation();
    const { toast } = useToast();


    const [includeTasks, setIncludeTasks] = useState(true);
    const [includeLabels, setIncludeLabels] = useState(true);
    const [includeSettings, setIncludeSettings] = useState(false);
    const [isExporting, setIsExporting] = useState(false);

    const handleExport = async () => {
        try {
            setIsExporting(true);
            const response = await apiRequest("POST", "/api/user/data-export", {
                includeTasks,
                includeLabels,
                includeSettings
            });

            if (!response.ok) throw new Error("Export failed");

            // Handle blob download
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `taskflow_export_${user?.username}_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);

            toast({ title: t('settings.export.success', "Data exported successfully") });
        } catch (error) {
            console.error(error);
            toast({
                title: t('settings.export.error', "Failed to export data"),
                variant: "destructive"
            });
        } finally {
            setIsExporting(false);
        }
    };

    return (
        <Card>
            <CardHeader>
                <CardTitle className="flex items-center gap-2">
                    <FileJson className="w-5 h-5" />
                    {t('settings.export.title')}
                </CardTitle>
                <CardDescription>
                    {t('settings.export.description')}
                </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
                <div className="flex items-center space-x-2">
                    <Checkbox
                        id="tasks"
                        checked={includeTasks}
                        onCheckedChange={(c) => setIncludeTasks(!!c)}
                    />
                    <Label htmlFor="tasks">{t('settings.export.tasks')}</Label>
                </div>

                <div className="flex items-center space-x-2">
                    <Checkbox
                        id="labels"
                        checked={includeLabels}
                        onCheckedChange={(c) => setIncludeLabels(!!c)}
                    />
                    <Label htmlFor="labels">{t('settings.export.labels')}</Label>
                </div>

                {user?.role === 'admin' && (
                    <div className="flex items-center space-x-2">
                        <Checkbox
                            id="settings"
                            checked={includeSettings}
                            onCheckedChange={(c) => setIncludeSettings(!!c)}
                        />
                        <Label htmlFor="settings">
                            {t('settings.export.systemSettings')}
                        </Label>
                    </div>
                )}
            </CardContent>
            <CardFooter>
                <Button
                    onClick={handleExport}
                    disabled={isExporting || (!includeTasks && !includeLabels && !includeSettings)}
                    data-testid="button-export-data"
                >
                    {isExporting ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Download className="mr-2 h-4 w-4" />}
                    {t('settings.export.button')}
                </Button>
            </CardFooter>
        </Card>
    );
}
