import { useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { useSettings } from "@/hooks/use-settings";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { insertUserSchema } from "@shared/schema";
import { Redirect } from "wouter";
import { Globe, Upload, Loader2 } from "lucide-react";
import { useLanguage } from "@/hooks/use-language";
import { Avatar, AvatarImage, AvatarFallback } from "@/components/ui/avatar";
import { useToast } from "@/hooks/use-toast";

export default function AuthPage() {
  const { user, loginMutation, registerMutation } = useAuth();
  const { settings, isLoading: isLoadingSettings } = useSettings();
  const { t, toggleLanguage, isArabic } = useLanguage();
  const { toast } = useToast();

  const loginForm = useForm({
    defaultValues: { username: "", password: "" }
  });

  const registerForm = useForm({
    resolver: zodResolver(insertUserSchema),
    defaultValues: { 
      username: "", 
      password: "", 
      name: "", 
      email: "",
      organization: "",
      position: "",
      phoneNumber: "",
      profileImage: "",
      role: "attendee" 
    }
  });

  const handleLogin = async (data: any) => {
    loginMutation.mutate(data);
  };

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

    try {
      const formData = new FormData();
      formData.append("file", file);

      const res = await fetch("/api/upload", {
        method: "POST",
        body: formData,
      });

      if (!res.ok) {
        throw new Error("Upload failed");
      }

      const { url } = await res.json();
      registerForm.setValue("profileImage", url, {
        shouldDirty: true,
        shouldValidate: true,
        shouldTouch: true
      });

      toast({
        title: t("Upload successful", "تم الرفع بنجاح"),
        description: t(
          "Profile photo has been uploaded",
          "تم رفع صورة الملف الشخصي"
        ),
      });
    } catch (error) {
      console.error("Upload error:", error);
      toast({
        title: t("Upload failed", "فشل الرفع"),
        description: t(
          "Failed to upload profile photo. Please try again.",
          "فشل رفع صورة الملف الشخصي. يرجى المحاولة مرة أخرى."
        ),
        variant: "destructive",
      });
    }
  };

  if (user) {
    return <Redirect to="/" />;
  }

  if (isLoadingSettings) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <Loader2 className="h-8 w-8 animate-spin text-primary" />
      </div>
    );
  }

  return (
    <div className="min-h-screen grid md:grid-cols-2 gap-8 items-center p-4" dir={isArabic ? "rtl" : "ltr"}>
      <Card className="w-full max-w-md mx-auto">
        <CardHeader>
          <CardTitle>{isArabic ? settings?.authWelcomeTitleAr : settings?.authWelcomeTitle}</CardTitle>
          <CardDescription>{isArabic ? settings?.authDescriptionAr : settings?.authDescription}</CardDescription>
        </CardHeader>
        <CardContent>
          <Tabs defaultValue="login">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="login">{t("Login", "تسجيل الدخول")}</TabsTrigger>
              <TabsTrigger value="register" disabled={!settings?.enableRegistration}>
                {t("Register", "تسجيل")}
              </TabsTrigger>
            </TabsList>

            <TabsContent value="login">
              <form onSubmit={loginForm.handleSubmit(handleLogin)}>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="login-username">{t("Username", "اسم المستخدم")}</Label>
                    <Input
                      id="login-username"
                      {...loginForm.register("username")}
                    />
                  </div>
                  <div>
                    <Label htmlFor="login-password">{t("Password", "كلمة المرور")}</Label>
                    <Input
                      id="login-password"
                      type="password"
                      {...loginForm.register("password")}
                    />
                  </div>
                  <Button
                    type="submit"
                    className="w-full"
                    disabled={loginMutation.isPending}
                  >
                    {loginMutation.isPending && (
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    )}
                    {t("Login", "تسجيل الدخول")}
                  </Button>
                </div>
              </form>
            </TabsContent>

            {settings?.enableRegistration && (
              <TabsContent value="register">
                <form onSubmit={registerForm.handleSubmit((data) => registerMutation.mutate(data))}>
                  <div className="space-y-4">
                    <div className="flex flex-col items-center space-y-2">
                      <Label htmlFor="profileImage">{t("Profile Picture", "الصورة الشخصية")}</Label>
                      <Avatar className="h-24 w-24">
                        <AvatarImage 
                          src={registerForm.getValues("profileImage") || `https://placehold.co/400x400?text=${registerForm.getValues("name") || "?"}`} 
                          alt={t("Profile picture", "الصورة الشخصية")} 
                        />
                        <AvatarFallback>?</AvatarFallback>
                      </Avatar>
                      <div className="flex items-center space-x-2">
                        <Input
                          id="profileImage"
                          type="file"
                          accept="image/*"
                          className="hidden"
                          onChange={handleFileUpload}
                        />
                        <Button
                          type="button"
                          variant="outline"
                          onClick={() => document.getElementById("profileImage")?.click()}
                        >
                          <Upload className="w-4 h-4 mr-2" />
                          {t("Upload Picture", "رفع صورة")}
                        </Button>
                      </div>
                    </div>
                    <div>
                      <Label htmlFor="register-name">{t("Full Name", "الاسم الكامل")}</Label>
                      <Input
                        id="register-name"
                        {...registerForm.register("name")}
                      />
                    </div>
                    <div>
                      <Label htmlFor="register-email">{t("Email", "البريد الإلكتروني")}</Label>
                      <Input
                        id="register-email"
                        type="email"
                        {...registerForm.register("email")}
                      />
                    </div>
                    <div>
                      <Label htmlFor="register-username">{t("Username", "اسم المستخدم")}</Label>
                      <Input
                        id="register-username"
                        {...registerForm.register("username")}
                      />
                    </div>
                    <div>
                      <Label htmlFor="register-password">{t("Password", "كلمة المرور")}</Label>
                      <Input
                        id="register-password"
                        type="password"
                        {...registerForm.register("password")}
                      />
                    </div>
                    <div>
                      <Label htmlFor="register-organization">{t("Organization", "المؤسسة")}</Label>
                      <Input
                        id="register-organization"
                        {...registerForm.register("organization")}
                      />
                    </div>
                    <div>
                      <Label htmlFor="register-position">{t("Position", "المنصب")}</Label>
                      <Input
                        id="register-position"
                        {...registerForm.register("position")}
                      />
                    </div>
                    <div>
                      <Label htmlFor="register-phone">{t("Phone Number", "رقم الهاتف")}</Label>
                      <Input
                        id="register-phone"
                        type="tel"
                        {...registerForm.register("phoneNumber")}
                      />
                    </div>
                    <Button
                      type="submit"
                      className="w-full"
                      disabled={registerMutation.isPending}
                    >
                      {registerMutation.isPending && (
                        <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      )}
                      {t("Register", "تسجيل")}
                    </Button>
                  </div>
                </form>
              </TabsContent>
            )}
          </Tabs>

          <Button 
            variant="outline" 
            className="w-full mt-4" 
            onClick={toggleLanguage}
          >
            <Globe className="w-4 h-4 mr-2" />
            {t("Switch to Arabic", "Switch to English")}
          </Button>
        </CardContent>
      </Card>

      <div className="hidden md:block text-center space-y-4">
        <h1 className="text-4xl font-bold">{isArabic ? settings?.siteTitleAr : settings?.siteTitle}</h1>
        <p className="text-xl text-muted-foreground">
          {isArabic ? settings?.authDescriptionAr : settings?.authDescription}
        </p>
        <div className="grid grid-cols-2 gap-4 mt-8">
          <div className="p-4 rounded-lg bg-primary/10">
            <h3 className="font-semibold">{isArabic ? settings?.statsCard1TitleAr : settings?.statsCard1Title}</h3>
            <p className="text-sm text-muted-foreground">{isArabic ? settings?.statsCard1DescriptionAr : settings?.statsCard1Description}</p>
          </div>
          <div className="p-4 rounded-lg bg-primary/10">
            <h3 className="font-semibold">{isArabic ? settings?.statsCard2TitleAr : settings?.statsCard2Title}</h3>
            <p className="text-sm text-muted-foreground">{isArabic ? settings?.statsCard2DescriptionAr : settings?.statsCard2Description}</p>
          </div>
        </div>
      </div>
    </div>
  );
}