'use client';

import { FileUpload } from '@/components/FileUpload';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { ProfileService, type ProfileData } from '@/lib/profile-service';
import { toReachableAbsoluteUrl } from '@/lib/url-utils';
import { zodResolver } from '@hookform/resolvers/zod';
import { Building, Calendar, Lock, LogOut, Mail, Save, Stethoscope, User } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

const updateProfileSchema = z.object({
  firstName: z.string().min(2),
  lastName: z.string().min(2),
  phone: z.string().optional(),
  specialization: z.string().optional(),
  licenseNumber: z.string().optional(),
  clinicName: z.string().optional(),
  clinicAddress: z.string().optional(),
  clinicPhone: z.string().optional(),
});

const changePasswordSchema = z.object({
  currentPassword: z.string().min(6),
  newPassword: z.string().min(6),
  confirmPassword: z.string(),
}).refine((data) => data.newPassword === data.confirmPassword, {
  message: 'Passwords do not match',
  path: ['confirmPassword'],
});

type UpdateProfileInput = z.infer<typeof updateProfileSchema>;
type ChangePasswordInput = z.infer<typeof changePasswordSchema>;

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;
};

const getAssetUrl = (value?: string) => {
  if (!value) return '';
  return toReachableAbsoluteUrl(value, API_BASE_URL);
};

export default function ProfilePage() {
  const router = useRouter();
  const { t, language, setLanguage } = useLanguage();
  const [profile, setProfile] = useState<ProfileData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  useEffect(() => {
    loadProfile();
  }, []);

  const loadProfile = async () => {
    try {
      setIsLoading(true);
      const response = await ProfileService.getProfile();

      if (!response.success) {
        setError(response.error || t('errors.serverError'));
        if (response.error?.includes('token')) {
          setTimeout(() => router.push('/login'), 2000);
        }
        return;
      }

      if (!response.user) {
        setProfile(null);
        return;
      }

      const normalizedProfile: ProfileData = {
        ...response.user,
        phone: normalizeText(response.user.phone),
        clinic: {
          name: normalizeText(response.user.clinic?.name),
          address: normalizeText(response.user.clinic?.address),
          phone: normalizeText(response.user.clinic?.phone),
        },
      };
      setProfile(normalizedProfile);
      // Set language from user profile if available
      if (response.user?.language && (response.user.language === 'es' || response.user.language === 'en')) {
        setLanguage(response.user.language);
      }
    } catch (err: any) {
      setError(t('errors.serverError'));
    } finally {
      setIsLoading(false);
    }
  };

  const handleLogout = () => {
    const { AuthService } = require('@/lib/auth-service');
    AuthService.logout();
    router.push('/login');
  };

  const handleLanguageChange = async (newLanguage: 'es' | 'en') => {
    setLanguage(newLanguage);
    try {
      await ProfileService.updateProfile({ language: newLanguage });
    } catch (err) {
      console.error('Failed to update language preference:', err);
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">{t('common.loading')}</p>
        </div>
      </div>
    );
  }

  if (!profile) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 px-4">
        <div className="w-full max-w-md">
          <Alert variant="destructive">
            <AlertDescription>
              {error || t('errors.serverError')}
            </AlertDescription>
          </Alert>
          <Button onClick={loadProfile} className="w-full mt-4 min-h-16 py-5 px-4 text-lg">
            {t('errors.tryAgain')}
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8 md:px-4">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="flex justify-between items-center mb-8">
          <div>
            <h1 className="text-4xl font-bold text-gray-900 mb-2">{t('profile.myProfile')}</h1>
            <p className="text-gray-600">{t('profile.editProfile')}</p>
          </div>
          <Button
            onClick={handleLogout}
            variant="outline"
            className="flex items-center gap-2 min-h-12 py-5 px-4 text-lg"
          >
            <LogOut className="w-4 h-4" />
            {t('navigation.logout')}
          </Button>
        </div>

        {/* Alerts */}
        {error && (
          <Alert variant="destructive" className="mb-6">
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

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

        {/* Main Content */}
        <Tabs defaultValue="details" className="w-full relative">
          <TabsList className="grid w-full grid-cols-1 md:grid-cols-3 mb-6 !h-auto md:!h-14">
            <TabsTrigger value="details" className='h-12'>{t('profile.personalInfo')}</TabsTrigger>
            <TabsTrigger value="security" className='h-12'>{t('profile.changePassword')}</TabsTrigger>
            <TabsTrigger value="settings" className='h-12'>{t('navigation.settings')}</TabsTrigger>
          </TabsList>

          {/* Profile Details Tab */}
          <TabsContent value="details" className="space-y-6 relative">
            {/* Profile Overview Card */}
            <Card>
              <CardHeader className="pb-4">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-16 rounded-full bg-linear-to-br from-blue-400 to-blue-600 flex items-center justify-center text-white text-2xl font-bold overflow-hidden relative">
                    {profile.profileImage ? (
                      <img
                        src={getAssetUrl(profile.profileImage)}
                        alt={t('profile.profileImage')}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <span>{profile.firstName.charAt(0)}{profile.lastName.charAt(0)}</span>
                    )}
                  </div>
                  <div>
                    <CardTitle className="text-2xl">
                      {profile.firstName} {profile.lastName}
                    </CardTitle>
                    <CardDescription className="capitalize">
                      {t(`auth.${profile.userType.toLowerCase()}`)}
                    </CardDescription>
                  </div>
                </div>
              </CardHeader>
            </Card>

            {/* Basic Information */}
            <Card>
              <CardHeader>
                <CardTitle>{t('profile.personalInfo')}</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="mb-6">
                  <label className="block text-sm font-medium text-gray-700 mb-2">{t('profile.profileImage')}</label>
                  <div className="flex items-center gap-6">
                    <FileUpload
                      onFileSelect={async (file) => {
                        try {
                          setIsLoading(true);
                          const result = await ProfileService.uploadProfileImage(file);
                          if (result.success && result.filePath) {
                            setSuccess(t('profile.profileImageUploadSuccess'));
                            // Update local state to reflect new image immediately if needed, 
                            // though loadProfile should handle it or we can manually update profile state
                            if (profile) {
                              setProfile({ ...profile, profileImage: result.filePath });
                            }
                            setTimeout(() => setSuccess(null), 3000);
                          } else {
                            setError(result.error || t('profile.profileImageUploadFailed'));
                            setTimeout(() => setError(null), 3000);
                          }
                        } catch (err) {
                          setError(t('profile.profileImageUploadFailed'));
                        } finally {
                          setIsLoading(false);
                        }
                      }}
                      previewUrl={profile.profileImage ? getAssetUrl(profile.profileImage) : undefined}
                      className="max-w-xs"
                    />
                  </div>
                </div>

                <UpdateProfileForm
                  profile={profile}
                  onSuccess={() => {
                    setSuccess(t('profile.successUpdate'));
                    loadProfile();
                    setTimeout(() => setSuccess(null), 3000);
                  }}
                  onError={(err) => {
                    setError(err);
                    setTimeout(() => setError(null), 3000);
                  }}
                />
              </CardContent>
            </Card>

            {/* Doctor Signature Section */}
            {(profile.userType === 'doctor' || profile.userType === 'dentist') && (
              <Card>
                <CardHeader>
                  <CardTitle>{t('profile.signature')}</CardTitle>
                  <CardDescription>{t('profile.signatureDesc')}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="mb-6">
                    <FileUpload
                      onFileSelect={async (file) => {
                        try {
                          setIsLoading(true);
                          const result = await ProfileService.uploadSignature(file);
                          if (result.success) {
                            if (profile && result.filePath) {
                              setProfile({
                                ...profile,
                                doctor: {
                                  ...(profile.doctor || {}),
                                  signatureUrl: result.filePath,
                                },
                              });
                            }
                            setSuccess(t('profile.signatureUploadSuccess'));
                            loadProfile();
                            setTimeout(() => setSuccess(null), 3000);
                          } else {
                            setError(result.error || t('profile.signatureUploadFailed'));
                            setTimeout(() => setError(null), 3000);
                          }
                        } catch (err) {
                          setError(t('profile.signatureUploadFailed'));
                        } finally {
                          setIsLoading(false);
                        }
                      }}
                      previewUrl={profile.doctor?.signatureUrl ? getAssetUrl(profile.doctor.signatureUrl) : undefined}
                      label={t('profile.uploadSignature')}
                      className="max-w-xs"
                      previewMode="contain"
                      previewBoxClassName="w-56 sm:w-64 h-24 bg-white p-1"
                    />
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Account Information */}
            <Card>
              <CardHeader>
                <CardTitle>{t('common.name')}</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                    <Mail className="w-5 h-5 text-blue-600" />
                    <div>
                      <p className="text-sm text-gray-600">{t('auth.email')}</p>
                      <p className="font-medium text-gray-900">{profile.email}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                    <User className="w-5 h-5 text-blue-600" />
                    <div>
                      <p className="text-sm text-gray-600">{t('auth.userType')}</p>
                      <p className="font-medium text-gray-900 capitalize">{t(`auth.${profile.userType.toLowerCase()}`)}</p>
                    </div>
                  </div>

                  <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                    <Calendar className="w-5 h-5 text-blue-600" />
                    <div>
                      <p className="text-sm text-gray-600">{t('profile.personalInfo')}</p>
                      <p className="font-medium text-gray-900">
                        {new Date(profile.createdAt).toLocaleDateString(language === 'es' ? 'es-ES' : 'en-US')}
                      </p>
                    </div>
                  </div>

                  {profile.lastLogin && (
                    <div className="flex items-center gap-4 p-4 bg-gray-50 rounded-lg">
                      <Calendar className="w-5 h-5 text-blue-600" />
                      <div>
                        <p className="text-sm text-gray-600">{t('common.name')}</p>
                        <p className="font-medium text-gray-900">
                          {new Date(profile.lastLogin).toLocaleString(language === 'es' ? 'es-ES' : 'en-US')}
                        </p>
                      </div>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Security Tab */}
          <TabsContent value="security" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Lock className="w-5 h-5" />
                  {t('profile.changePassword')}
                </CardTitle>
                <CardDescription>
                  {t('profile.successPasswordChange')}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <ChangePasswordForm
                  onSuccess={() => {
                    setSuccess(t('profile.successPasswordChange'));
                    setTimeout(() => setSuccess(null), 3000);
                  }}
                  onError={(err) => {
                    setError(err);
                    setTimeout(() => setError(null), 3000);
                  }}
                />
              </CardContent>
            </Card>

            {/* Security Tips */}
            <Card className="border-blue-200 bg-blue-50">
              <CardHeader>
                <CardTitle className="text-blue-900">{t('common.warning')}</CardTitle>
              </CardHeader>
              <CardContent className="text-blue-800">
                <ul className="space-y-2 text-sm">
                  <li>✓ {t('auth.charMinimum')}</li>
                  <li>✓ {t('auth.oneUppercase')}</li>
                  <li>✓ {t('auth.oneLowercase')}</li>
                  <li>✓ {t('auth.oneNumber')}</li>
                  <li>✓ {t('auth.oneSpecial')}</li>
                </ul>
              </CardContent>
            </Card>
          </TabsContent>

          {/* Settings Tab */}
          <TabsContent value="settings" className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>{t('navigation.settings')}</CardTitle>
                <CardDescription>{t('profile.selectLanguage')}</CardDescription>
              </CardHeader>
              <CardContent className="space-y-6">
                <div className="space-y-4">
                  <label className="text-sm font-medium">{t('profile.language')}</label>
                  <Select value={language} onValueChange={(value) => handleLanguageChange(value as 'es' | 'en')}>
                    <SelectTrigger className="h-12">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="es">{t('profile.spanish')}</SelectItem>
                      <SelectItem value="en">{t('profile.english')}</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
}

// Update Profile Form Component
function UpdateProfileForm({
  profile,
  onSuccess,
  onError,
}: {
  profile: ProfileData;
  onSuccess: () => void;
  onError: (error: string) => void;
}) {
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const isDoctor = profile.userType === 'doctor' || profile.userType === 'dentist';
  const form = useForm<UpdateProfileInput>({
    resolver: zodResolver(updateProfileSchema),
    defaultValues: {
      firstName: profile.firstName,
      lastName: profile.lastName,
      phone: normalizeText(profile.phone),
      specialization: normalizeText(profile.doctor?.specialization),
      licenseNumber: normalizeText(profile.doctor?.licenseNumber),
      clinicName: normalizeText(profile.clinic?.name),
      clinicAddress: normalizeText(profile.clinic?.address),
      clinicPhone: normalizeText(profile.clinic?.phone),
    },
  });

  const onSubmit = async (data: UpdateProfileInput) => {
    setIsLoading(true);
    try {
      const response = await ProfileService.updateProfile({
        firstName: data.firstName,
        lastName: data.lastName,
        phone: data.phone || undefined,
        ...(isDoctor ? {
          specialization: data.specialization || undefined,
          licenseNumber: data.licenseNumber || undefined,
          clinic: {
            name: data.clinicName || undefined,
            address: data.clinicAddress || undefined,
            phone: data.clinicPhone || undefined,
          },
        } : {}),
      });

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

      onSuccess();
    } catch (err: any) {
      onError(t('errors.serverError'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <FormField
            control={form.control}
            name="firstName"
            render={({ field }) => (
              <FormItem>
                <FormLabel>{t('auth.firstName')}</FormLabel>
                <FormControl>
                  <Input {...field} disabled={isLoading} className='h-12' />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="lastName"
            render={({ field }) => (
              <FormItem>
                <FormLabel>{t('auth.lastName')}</FormLabel>
                <FormControl>
                  <Input {...field} disabled={isLoading} className='h-12' />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        <FormField
          control={form.control}
          name="phone"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t('auth.phone')}</FormLabel>
              <FormControl>
                <Input
                  type="tel"
                  placeholder="+1 (555) 000-0000"
                  {...field}
                  disabled={isLoading}
                  className='h-12'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        {/* Doctor-specific fields */}
        {isDoctor && (
          <div className="border-t pt-6 mt-2">
            <h3 className="font-medium text-gray-900 mb-4 flex items-center gap-2">
              <Stethoscope className="w-5 h-5 text-blue-600" />
              {t('profile.doctorInfo')}
            </h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <FormField
                control={form.control}
                name="specialization"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t('profile.specialization')}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t('profile.specializationPlaceholder')}
                        {...field}
                        disabled={isLoading}
                        className="h-12"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="licenseNumber"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t('profile.licenseNumber')}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t('profile.licenseNumberPlaceholder')}
                        {...field}
                        disabled={isLoading}
                        className="h-12"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
          </div>
        )}

        {/* Clinic Information (Doctor only) */}
        {isDoctor && (
          <div className="border-t pt-6 mt-2">
            <h3 className="font-medium text-gray-900 mb-4 flex items-center gap-2">
              <Building className="w-5 h-5 text-blue-600" />
              {t('profile.clinicInfo')}
            </h3>
            <div className="space-y-4">
              <FormField
                control={form.control}
                name="clinicName"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t('profile.clinicName')}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t('profile.clinicNamePlaceholder')}
                        {...field}
                        disabled={isLoading}
                        className="h-12"
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <FormField
                  control={form.control}
                  name="clinicAddress"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t('profile.clinicAddress')}</FormLabel>
                      <FormControl>
                        <Input
                          placeholder={t('profile.clinicAddressPlaceholder')}
                          {...field}
                          disabled={isLoading}
                          className="h-12"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="clinicPhone"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>{t('profile.clinicPhone')}</FormLabel>
                      <FormControl>
                        <Input
                          placeholder={t('profile.clinicPhonePlaceholder')}
                          {...field}
                          disabled={isLoading}
                          className="h-12"
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>
          </div>
        )}


        <Button
          type="submit"
          disabled={isLoading}
          className="flex items-center gap-2 min-h-12 py-5 px-4 text-lg"
        >
          <Save className="w-4 h-4" />
          {isLoading ? t('common.loading') : t('common.save')}
        </Button>
      </form>
    </Form>
  );
}

// Change Password Form Component
function ChangePasswordForm({
  onSuccess,
  onError,
}: {
  onSuccess: () => void;
  onError: (error: string) => void;
}) {
  const { t } = useLanguage();
  const [isLoading, setIsLoading] = useState(false);
  const form = useForm<ChangePasswordInput>({
    resolver: zodResolver(changePasswordSchema),
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  });

  const onSubmit = async (data: ChangePasswordInput) => {
    setIsLoading(true);
    try {
      const response = await ProfileService.changePassword({
        currentPassword: data.currentPassword,
        newPassword: data.newPassword,
        confirmPassword: data.confirmPassword,
      });

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

      form.reset();
      onSuccess();
    } catch (err: any) {
      onError(t('errors.serverError'));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
        <FormField
          control={form.control}
          name="currentPassword"
          render={({ field }) => (
            <FormItem>
              <FormLabel>{t('profile.currentPassword')}</FormLabel>
              <FormControl>
                <Input
                  type="password"
                  placeholder={t('profile.currentPassword')}
                  {...field}
                  disabled={isLoading}
                  className='h-12'
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <div className="border-t pt-6"> 
          <div className="space-y-4">
            <FormField
              control={form.control}
              name="newPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('profile.newPassword')}</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder={t('profile.newPassword')}
                      {...field}
                      disabled={isLoading}
                      className='h-12'
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="confirmPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('profile.confirmPassword')}</FormLabel>
                  <FormControl>
                    <Input
                      type="password"
                      placeholder={t('profile.confirmPassword')}
                      {...field}
                      disabled={isLoading}
                      className='h-12'
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>

        <Button
          type="submit"
          disabled={isLoading}
          className="flex items-center gap-2 min-h-12 py-5 px-4 text-lg"
        >
          <Lock className="w-4 h-4" />
          {isLoading ? t('common.loading') : t('profile.changePasswordBtn')}
        </Button>
      </form>
    </Form>
  );
}
