import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Building2, Calendar, Globe, Loader2, Upload, User as UserIcon } from 'lucide-react';
import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Separator } from '@/components/ui/separator';
import { getMyProfile, updateMyProfile } from '@/client';
import {getApiErrorMessage} from '@/lib/api-error';

export function SettingsProfile() {
    const queryClient = useQueryClient();
    const [avatarUrl, setAvatarUrl] = useState('');
    const [websiteUrl, setWebsiteUrl] = useState('');
    const [organization, setOrganization] = useState('');
    const [originalAvatarUrl, setOriginalAvatarUrl] = useState('');
    const [originalWebsiteUrl, setOriginalWebsiteUrl] = useState('');
    const [originalOrganization, setOriginalOrganization] = useState('');

    const { data: profile, isLoading } = useQuery({
        queryKey: ['userProfile'],
        queryFn: async () => {
            const resp = await getMyProfile();
            return resp.data?.data ?? null;
        },
    });

    useEffect(() => {
        if (profile) {
            setAvatarUrl(profile.avatar_url || '');
            setWebsiteUrl(profile.website_url || '');
            setOrganization(profile.organization || '');
            setOriginalAvatarUrl(profile.avatar_url || '');
            setOriginalWebsiteUrl(profile.website_url || '');
            setOriginalOrganization(profile.organization || '');
        }
    }, [profile]);

    const hasChanges =
        avatarUrl !== originalAvatarUrl ||
        websiteUrl !== originalWebsiteUrl ||
        organization !== originalOrganization;

	const uploadAvatarMutation = useMutation({
		mutationFn: async (file: File) => {
			const baseUrl = import.meta.env.VITE_API_BASE_URL ?? '';
			const formData = new FormData();
			formData.append('file', file);
			const res = await fetch(`${baseUrl}/api/users/me/avatar`, {
				method: 'POST',
				body: formData,
				credentials: 'include',
			});
			if (!res.ok) {
				const err = await res.json().catch(() => null);
				throw new Error(err?.message ?? 'Upload failed');
			}
			const json = await res.json();
			return json as { data?: { avatar_url?: string } };
		},
		onSuccess: (data) => {
			toast.success('Avatar uploaded successfully');
			const url = data?.data?.avatar_url;
			if (url) setAvatarUrl(url);
			queryClient.invalidateQueries({ queryKey: ['userProfile'] });
		},
		onError: (err: Error) => {
			toast.error(err.message || 'Failed to upload avatar');
		},
	});

	const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		if (!file) return;

		if (file.size > 2 * 1024 * 1024) {
			toast.error('File size must be less than 2MB');
			return;
		}

		uploadAvatarMutation.mutate(file);
	};

    const updateProfileMutation = useMutation({
        mutationFn: async () => {
            await updateMyProfile({
                body: {
                    website_url: websiteUrl || null,
                    organization: organization || null,
                },
            });
        },
        onSuccess: () => {
            toast.success('Profile updated successfully');
            queryClient.invalidateQueries({ queryKey: ['userProfile'] });
            setOriginalAvatarUrl(avatarUrl);
            setOriginalWebsiteUrl(websiteUrl);
            setOriginalOrganization(organization);
        },
        onError: (err: unknown) => {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            toast.error(getApiErrorMessage(err, 'Failed to update profile'));
        },
    });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        updateProfileMutation.mutate();
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
        });
    };

    if (isLoading) {
        return (
            <div className="flex items-center justify-center p-8">
                <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
            </div>
        );
    }

    return (
        <div className="flex-1 lg:max-w-4xl space-y-6 p-4 md:p-8 pt-6">
            <div className="space-y-0.5">
                <h2 className="text-2xl font-bold tracking-tight">Profile</h2>
                <p className="text-muted-foreground">Manage your personal information and profile settings.</p>
            </div>
            <Separator className="my-6" />

            {/* Profile Information Card */}
            <Card className="mb-6">
                <CardHeader>
                    <CardTitle>Profile Information</CardTitle>
                    <p className="text-sm text-muted-foreground">View your basic account information.</p>
                </CardHeader>
                <CardContent className="space-y-4">
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div className="space-y-2">
                            <Label className="text-muted-foreground">Username</Label>
                            <div className="flex items-center gap-2">
                                <UserIcon className="h-4 w-4 text-muted-foreground" />
                                <span className="font-medium">{profile?.username}</span>
                            </div>
                        </div>
                        <div className="space-y-2">
                            <Label className="text-muted-foreground">Display Name</Label>
                            <div className="flex items-center gap-2">
                                <UserIcon className="h-4 w-4 text-muted-foreground" />
                                <span className="font-medium">{profile?.display_name || 'Not set'}</span>
                            </div>
                        </div>
                        <div className="space-y-2">
                            <Label className="text-muted-foreground">Email</Label>
                            <div className="flex items-center gap-2">
                                <span className="font-medium text-sm">N/A</span>
                            </div>
                        </div>
                        <div className="space-y-2">
                            <Label className="text-muted-foreground">Member Since</Label>
                            <div className="flex items-center gap-2">
                                <Calendar className="h-4 w-4 text-muted-foreground" />
                                <span>{profile?.created_at ? formatDate(profile.created_at) : 'N/A'}</span>
                            </div>
                        </div>
                    </div>
                </CardContent>
            </Card>

            {/* Update Profile Card */}
            <Card>
                <CardHeader>
                    <CardTitle>Public Profile</CardTitle>
                    <p className="text-sm text-muted-foreground">Update your public profile information.</p>
                </CardHeader>
                <CardContent>
                    <form onSubmit={handleSubmit} className="space-y-6">
                        <div className="space-y-4">
                            <Label>Public Avatar</Label>
                            <div className="flex flex-col md:flex-row gap-6 items-start">
                                <div className="shrink-0">
                                    <div className="h-24 w-24 rounded-full border-2 border-muted bg-muted/50 flex items-center justify-center overflow-hidden relative group">
                                        {avatarUrl ? (
                                            <img
                                                src={avatarUrl}
                                                alt="Avatar preview"
                                                className="h-full w-full object-cover"
                                                onError={(e) => {
                                                    e.currentTarget.style.display = 'none';
                                                }}
                                            />
                                        ) : (
                                            <UserIcon className="h-12 w-12 text-muted-foreground/50" />
                                        )}
                                        {uploadAvatarMutation.isPending && (
                                            <div className="absolute inset-0 bg-background/50 flex items-center justify-center">
                                                <Loader2 className="h-6 w-6 animate-spin text-foreground" />
                                            </div>
                                        )}
                                    </div>
                                </div>
                                <div className="flex-1 space-y-4 w-full">
                                    <div className="space-y-2">
                                        <Label className="text-xs text-muted-foreground uppercase font-semibold">
                                            Upload Avatar
                                        </Label>
                                        <div className="flex items-center gap-4">
                                            <Button
                                                type="button"
                                                variant="outline"
                                                size="sm"
                                                onClick={() => document.getElementById('avatar-upload')?.click()}
                                                disabled={uploadAvatarMutation.isPending}
                                            >
                                                <Upload className="h-4 w-4 mr-2" />
                                                Upload new avatar
                                            </Button>
                                            <Input
                                                id="avatar-upload"
                                                type="file"
                                                className="hidden"
                                                accept="image/png,image/jpeg,image/gif,image/webp"
                                                onChange={handleFileChange}
                                            />
                                            <span className="text-xs text-muted-foreground">JPG, GIF or PNG. Max size 2MB.</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <Separator />

                        <div className="grid gap-6 md:grid-cols-2">
                            <div className="space-y-2">
                                <Label htmlFor="bio">Bio</Label>
                                <div className="flex items-center gap-2">
                                    <Globe className="h-4 w-4 text-muted-foreground" />
                                    <Input
                                        id="bio"
                                        type="text"
                                        placeholder="Tell us about yourself"
                                        value={websiteUrl}
                                        onChange={(e) => setWebsiteUrl(e.target.value)}
                                        className="flex-1"
                                    />
                                </div>
                                <p className="text-xs text-muted-foreground">Your bio or description</p>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="organization">Organization</Label>
                                <div className="flex items-center gap-2">
                                    <Building2 className="h-4 w-4 text-muted-foreground" />
                                    <Input
                                        id="organization"
                                        type="text"
                                        placeholder="Your company or organization"
                                        value={organization}
                                        onChange={(e) => setOrganization(e.target.value)}
                                        className="flex-1"
                                    />
                                </div>
                                <p className="text-xs text-muted-foreground">The organization you belong to</p>
                            </div>
                        </div>

                        <div className="flex justify-end gap-2 pt-4">
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setAvatarUrl(originalAvatarUrl);
                                    setWebsiteUrl(originalWebsiteUrl);
                                    setOrganization(originalOrganization);
                                }}
                                disabled={updateProfileMutation.isPending || !hasChanges}
                            >
                                Reset
                            </Button>
                            <Button type="submit" disabled={updateProfileMutation.isPending || !hasChanges}>
                                {updateProfileMutation.isPending ? (
                                    <>
                                        <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                                        Saving...
                                    </>
                                ) : (
                                    'Save Changes'
                                )}
                            </Button>
                        </div>
                    </form>
                </CardContent>
            </Card>
        </div>
    );
}
