import { useState } from 'react';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Switch } from '@/components/ui/switch';
import { Textarea } from '@/components/ui/textarea';
import { projectExchangeTitle, projectExchangeVisibility } from '@/client';
import { useProject } from '@/contexts';
import {getApiErrorMessage} from '@/lib/api-error';

export function SettingsGeneral() {
    const { project, refetch } = useProject();

    const [loading, setLoading] = useState(false);
    const [confirmOpen, setConfirmOpen] = useState(false);

    const [displayName, setDisplayName] = useState(project?.display_name || '');
    const [description, setDescription] = useState(project?.description || '');
    const [isPublic, setIsPublic] = useState(project?.is_public ?? false);

    const hasChanges =
        displayName !== (project?.display_name || '') ||
        description !== (project?.description || '') ||
        isPublic !== (project?.is_public ?? false);

    const handleSave = async () => {
        if (!project?.name) return;

        setLoading(true);
        try {
            await projectExchangeTitle({
                path: { project_name: project.name },
                body: {
                    display_name: displayName || null,
                    description: description || null,
                },
            });

            await projectExchangeVisibility({
                path: { project_name: project.name },
                body: { is_public: isPublic },
            });

            toast.success('Project settings updated');
            setConfirmOpen(false);
            refetch();
        } catch (err: unknown) {
            toast.error(
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                getApiErrorMessage(err, 'Failed to update project settings'),
            );
        } finally {
            setLoading(false);
        }
    };

    if (!project) return null;

    return (
        <>
            <Card className="border-border/50 shadow-sm">
                <CardHeader className="pb-4">
                    <CardTitle className="text-lg">General</CardTitle>
                    <CardDescription>
                        Manage your project basic information and visibility.
                    </CardDescription>
                </CardHeader>

                <CardContent className="space-y-6 pt-2">
                    <div className="space-y-2">
                        <Label htmlFor="display-name">Display Name</Label>
                        <Input
                            id="display-name"
                            value={displayName}
                            onChange={(e) => setDisplayName(e.target.value)}
                            disabled={loading}
                            className="h-10"
                        />
                    </div>

                    <div className="space-y-2">
                        <Label htmlFor="description">Description</Label>
                        <Textarea
                            id="description"
                            value={description}
                            onChange={(e) => setDescription(e.target.value)}
                            rows={3}
                            disabled={loading}
                            className="resize-none"
                        />
                    </div>

                    <div className="flex items-center justify-between rounded-lg border p-4">
                        <div className="space-y-1">
                            <Label className="text-sm font-medium">Public Visibility</Label>
                            <p className="text-sm text-muted-foreground">
                                Allow anyone to view this project.
                            </p>
                        </div>
                        <Switch checked={isPublic} onCheckedChange={setIsPublic} disabled={loading} />
                    </div>
                </CardContent>

                <CardFooter className="flex justify-end pt-2">
                    <Button onClick={() => setConfirmOpen(true)} disabled={loading || !hasChanges}>
                        Save Changes
                    </Button>
                </CardFooter>
            </Card>

            <AlertDialog open={confirmOpen} onOpenChange={setConfirmOpen}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>Confirm project changes</AlertDialogTitle>
                        <AlertDialogDescription className="space-y-2">
                            <p>You are about to update the following settings:</p>
                            <ul className="list-disc pl-5 text-sm">
                                <li>Display name</li>
                                <li>Description</li>
                                <li>Visibility: {isPublic ? 'Public' : 'Private'}</li>
                            </ul>
                            {isPublic && (
                                <p className="text-sm text-amber-600 dark:text-amber-500">
                                    Making this project public will allow anyone to view its content.
                                </p>
                            )}
                        </AlertDialogDescription>
                    </AlertDialogHeader>

                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={loading}>Cancel</AlertDialogCancel>
                        <AlertDialogAction onClick={handleSave} disabled={loading}>
                            {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                            Confirm &amp; Save
                        </AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
}
