'use client';

import { Alert, AlertDescription } from '@/components/ui/alert';
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 { useLanguage } from '@/lib/language-context';
import { ProfileService } from '@/lib/profile-service';
import { Save } from 'lucide-react';
import { useEffect, useState } from 'react';

const normalizeText = (value?: string | null): string => {
    if (value === null || value === undefined) return '';
    const trimmed = String(value).trim();
    if (!trimmed || trimmed.toLowerCase() === 'null' || trimmed.toLowerCase() === 'undefined') return '';
    return trimmed;
};

export default function SettingsPage() {
    const { t } = useLanguage();
    const [clinicName, setClinicName] = useState('');
    const [clinicAddress, setClinicAddress] = useState('');
    const [clinicPhone, setClinicPhone] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);

    useEffect(() => {
        const loadSettings = async () => {
            try {
                setIsLoading(true);
                const response = await ProfileService.getProfile();
                if (!response.success || !response.user) {
                    setError(response.error || t('errors.serverError'));
                    return;
                }
                setClinicName(normalizeText(response.user.clinic?.name));
                setClinicAddress(normalizeText(response.user.clinic?.address));
                setClinicPhone(normalizeText(response.user.clinic?.phone));
            } catch {
                setError(t('errors.serverError'));
            } finally {
                setIsLoading(false);
            }
        };

        loadSettings();
    }, [t]);

    const handleSave = async () => {
        setError(null);
        setSuccess(null);
        setIsSaving(true);
        try {
            const response = await ProfileService.updateProfile({
                clinic: {
                    name: normalizeText(clinicName) || undefined,
                    address: normalizeText(clinicAddress) || undefined,
                    phone: normalizeText(clinicPhone) || undefined,
                },
            });

            if (!response.success) {
                setError(response.error || t('errors.serverError'));
                return;
            }

            setClinicName(normalizeText(response.user?.clinic?.name) || normalizeText(clinicName));
            setClinicAddress(normalizeText(response.user?.clinic?.address) || normalizeText(clinicAddress));
            setClinicPhone(normalizeText(response.user?.clinic?.phone) || normalizeText(clinicPhone));
            setSuccess(t('profile.successUpdate'));
        } catch {
            setError(t('errors.serverError'));
        } finally {
            setIsSaving(false);
        }
    };

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between">
                <h1 className="text-3xl font-bold">{t('settings.title')}</h1>
            </div>

            {error && (
                <Alert variant="destructive">
                    <AlertDescription>{error}</AlertDescription>
                </Alert>
            )}
            {success && (
                <Alert className="border-green-500 bg-green-50">
                    <AlertDescription className="text-green-800">{success}</AlertDescription>
                </Alert>
            )}

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <Card>
                    <CardHeader>
                        <CardTitle>{t('settings.clinicInformation')}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div>
                            <Label htmlFor="clinicName">{t('settings.clinicName')}</Label>
                            <Input
                                id="clinicName"
                                value={clinicName}
                                onChange={(e) => setClinicName(e.target.value)}
                                placeholder={t('settings.clinicNamePlaceholder')}
                                className="h-12"
                                disabled={isLoading || isSaving}
                            />
                        </div>
                        <div>
                            <Label htmlFor="address">{t('common.address')}</Label>
                            <Input
                                id="address"
                                value={clinicAddress}
                                onChange={(e) => setClinicAddress(e.target.value)}
                                placeholder={t('settings.addressPlaceholder')}
                                className="h-12"
                                disabled={isLoading || isSaving}
                            />
                        </div>
                        <div>
                            <Label htmlFor="contact">{t('settings.contactNumber')}</Label>
                            <Input
                                id="contact"
                                value={clinicPhone}
                                onChange={(e) => setClinicPhone(e.target.value)}
                                placeholder={t('settings.contactNumberPlaceholder')}
                                className="h-12"
                                disabled={isLoading || isSaving}
                            />
                        </div>
                        <Button className="w-full h-12 gap-2" onClick={handleSave} disabled={isLoading || isSaving}>
                            <Save className="h-4 w-4" />
                            {isSaving ? t('common.loading') : t('settings.saveChanges')}
                        </Button>
                    </CardContent>
                </Card>

                <Card>
                    <CardHeader>
                        <CardTitle>{t('settings.applicationSettings')}</CardTitle>
                    </CardHeader>
                    <CardContent className="space-y-4">
                        <div className="flex items-center justify-between p-3 border rounded-lg">
                            <div>
                                <div className="font-medium">{t('settings.darkMode')}</div>
                                <div className="text-sm text-gray-500">{t('settings.darkModeDescription')}</div>
                            </div>
                            <Button variant="outline" size="sm" disabled>{t('settings.comingSoon')}</Button>
                        </div>
                        <div className="flex items-center justify-between p-3 border rounded-lg">
                            <div>
                                <div className="font-medium">{t('settings.notifications')}</div>
                                <div className="text-sm text-gray-500">{t('settings.notificationsDescription')}</div>
                            </div>
                            <Button variant="outline" size="sm" disabled>{t('settings.comingSoon')}</Button>
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
}
