"use client";
import { FormSuccess } from "@/components/form/FormSuccess";
import { FormError } from "@/components/form/FormError";
import { useState, useTransition } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Lock, User, Mail, Shield } from "lucide-react";
import { useSession } from "next-auth/react";
import { Switch } from "@/components/ui/switch";
import { settings } from "@/actions/settingsActions";
import { SettingsSchema, SettingsSchemaType } from "@/schemas/settings.schema";
import { z } from "zod";

// Only create a separate schema for the form UI to handle confirmPassword
const PasswordFormSchema = z
  .object({
    password: z.string().min(6, "Password must be at least 6 characters"),
    newPassword: z
      .string()
      .min(6, "New password must be at least 6 characters"),
    confirmPassword: z.string().min(6, "Confirm password is required"),
  })
  .refine((data) => data.newPassword === data.confirmPassword, {
    message: "Passwords don't match",
    path: ["confirmPassword"],
  });

type PasswordFormValues = z.infer<typeof PasswordFormSchema>;

export default function SettingsPage() {
  const [error, setError] = useState<string | undefined>();
  const [success, setSuccess] = useState<string | undefined>();
  const { data: session, update, status } = useSession();
  const [isPending, startTransition] = useTransition();
  console.log("Session data:", session);

  // Get user data only if session exists
  const userInfo = session?.user
    ? {
        isOAuth: session.user.isOAuth || false,
        isTwoFactorEnabled: session.user.isTwoFactorEnabled || false,
        role: session.user.role || "USER",
        email: session.user.email || "",
        image: session.user.image || "",
        name: session.user.name || "",
        id: session.user.id,
      }
    : null;

  // Profile form
  const profileForm = useForm<SettingsSchemaType>({
    resolver: zodResolver(SettingsSchema),
    defaultValues: {
      name: userInfo?.name || "",
    },
  });

  // Password form with confirmation field
  const passwordForm = useForm<PasswordFormValues>({
    resolver: zodResolver(PasswordFormSchema),
    defaultValues: {
      password: "",
      newPassword: "",
      confirmPassword: "",
    },
  });

  const onProfileSubmit = (values: SettingsSchemaType) => {
    setSuccess(undefined);
    setError(undefined);

    startTransition(() => {
      settings({ name: values.name })
        .then((data) => {
          if (data.error) {
            setError(data.error);
          }

          if (data.success) {
            update();
            setSuccess(data.success);
          }
        })
        .catch(() => setError("Something went wrong!"));
    });
  };

  const onPasswordSubmit = (values: PasswordFormValues) => {
    setSuccess(undefined);
    setError(undefined);

    // Remove confirmPassword field before sending to server
    const { confirmPassword, ...submitData } = values;

    startTransition(() => {
      // Make sure we're sending exactly what the server expects
      settings({
        password: submitData.password,
        newPassword: submitData.newPassword,
      })
        .then((data) => {
          if (data.error) {
            setError(data.error);
          }

          if (data.success) {
            passwordForm.reset({
              password: "",
              newPassword: "",
              confirmPassword: "",
            });
            setSuccess(data.success);
          }
        })
        .catch(() => setError("Something went wrong!"));
    });
  };

  const handleToggleTwoFactor = () => {
    if (!userInfo) return;

    setSuccess(undefined);
    setError(undefined);

    startTransition(() => {
      // Send only the isTwoFactorEnabled field, making sure it's properly typed
      settings({
        isTwoFactorEnabled: !userInfo.isTwoFactorEnabled,
      } as SettingsSchemaType)
        .then((data) => {
          if (data.error) {
            setError(data.error);
          }

          if (data.success) {
            update();
            setSuccess(data.success);
          }
        })
        .catch(() => setError("Something went wrong!"));
    });
  };

  if (status === "loading") {
    return (
      <div className="flex h-96 items-center justify-center">
        <div className="h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"></div>
      </div>
    );
  }

  if (!userInfo) {
    return (
      <div className="container mx-auto py-8 text-center">
        <h1 className="text-2xl font-bold">
          Please sign in to access settings
        </h1>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-6">
      {/* User Profile Header */}
      <div className="mb-8 flex flex-col items-center justify-center sm:flex-row sm:justify-start">
        <Avatar className="h-24 w-24 border-4 border-white shadow-md">
          <AvatarImage src={userInfo.image} alt={userInfo.name} />
          <AvatarFallback className="text-2xl">
            {userInfo.name?.charAt(0)?.toUpperCase() || "U"}
          </AvatarFallback>
        </Avatar>

        <div className="mt-4 text-center sm:ml-6 sm:mt-0 sm:text-left">
          <h1 className="text-3xl font-bold text-gray-900">{userInfo.name}</h1>
          <div className="mt-1 flex flex-wrap items-center gap-2">
            <p className="text-gray-500">{userInfo.email}</p>
            <Badge className="bg-[#03045E]">{userInfo.role}</Badge>
            {userInfo.isOAuth && (
              <Badge variant="outline" className="text-blue-600">
                OAuth Account
              </Badge>
            )}
          </div>
        </div>
      </div>

      <div className="mb-8">
        <h2 className="text-2xl font-bold text-gray-900">Account Settings</h2>
        <p className="mt-1 text-gray-500">
          Manage your account settings and preferences
        </p>
      </div>

      <Tabs defaultValue="profile" className="space-y-6">
        <TabsList className="grid w-full grid-cols-2">
          <TabsTrigger value="profile">Profile</TabsTrigger>
          <TabsTrigger value="security">Security</TabsTrigger>
        </TabsList>

        <TabsContent value="profile">
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle>Profile Information</CardTitle>
                  <CardDescription>
                    Manage your personal information
                  </CardDescription>
                </div>
              </div>
            </CardHeader>
            <Form {...profileForm}>
              <form onSubmit={profileForm.handleSubmit(onProfileSubmit)}>
                <CardContent className="space-y-6">
                  <div className="space-y-4">
                    <FormField
                      control={profileForm.control}
                      name="name"
                      render={({ field }) => (
                        <FormItem className="space-y-2">
                          <div className="flex items-center space-x-2">
                            <User className="h-4 w-4 text-gray-500" />
                            <FormLabel>Full Name</FormLabel>
                          </div>
                          <FormControl>
                            <Input {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <div className="space-y-2">
                      <div className="flex items-center space-x-2">
                        <Mail className="h-4 w-4 text-gray-500" />
                        <Label htmlFor="email">Email Address</Label>
                      </div>
                      <Input
                        id="email"
                        name="email"
                        type="email"
                        value={userInfo.email}
                        disabled
                        className="bg-gray-50"
                      />
                      <p className="text-xs text-gray-500">
                        Email cannot be changed. Contact support if needed.
                      </p>
                    </div>
                  </div>
                </CardContent>
                <CardFooter>
                  <Button
                    type="submit"
                    className="bg-[#03045E]"
                    disabled={isPending || !profileForm.formState.isDirty}
                  >
                    {isPending ? "Saving..." : "Save Changes"}
                  </Button>
                </CardFooter>
              </form>
            </Form>
          </Card>
        </TabsContent>

        <TabsContent value="security">
          <div className="grid gap-6">
            {/* Password Settings */}
            {!userInfo.isOAuth && (
              <Card>
                <CardHeader>
                  <CardTitle>Change Password</CardTitle>
                  <CardDescription>
                    Update your account password
                  </CardDescription>
                </CardHeader>
                <Form {...passwordForm}>
                  <form onSubmit={passwordForm.handleSubmit(onPasswordSubmit)}>
                    <CardContent className="space-y-6">
                      <div className="space-y-4">
                        <FormField
                          control={passwordForm.control}
                          name="password"
                          render={({ field }) => (
                            <FormItem className="space-y-2">
                              <div className="flex items-center space-x-2">
                                <Lock className="h-4 w-4 text-gray-500" />
                                <FormLabel>Current Password</FormLabel>
                              </div>
                              <FormControl>
                                <Input
                                  {...field}
                                  type="password"
                                  placeholder="••••••••"
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={passwordForm.control}
                          name="newPassword"
                          render={({ field }) => (
                            <FormItem className="space-y-2">
                              <div className="flex items-center space-x-2">
                                <Lock className="h-4 w-4 text-gray-500" />
                                <FormLabel>New Password</FormLabel>
                              </div>
                              <FormControl>
                                <Input
                                  {...field}
                                  type="password"
                                  placeholder="••••••••"
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />

                        <FormField
                          control={passwordForm.control}
                          name="confirmPassword"
                          render={({ field }) => (
                            <FormItem className="space-y-2">
                              <div className="flex items-center space-x-2">
                                <Lock className="h-4 w-4 text-gray-500" />
                                <FormLabel>Confirm Password</FormLabel>
                              </div>
                              <FormControl>
                                <Input
                                  {...field}
                                  type="password"
                                  placeholder="••••••••"
                                />
                              </FormControl>
                              <FormMessage />
                            </FormItem>
                          )}
                        />
                      </div>
                    </CardContent>
                    <CardFooter>
                      <Button
                        type="submit"
                        className="bg-[#03045E]"
                        disabled={isPending || !passwordForm.formState.isDirty}
                      >
                        {isPending ? "Updating..." : "Update Password"}
                      </Button>
                    </CardFooter>
                  </form>
                </Form>
              </Card>
            )}

            {/* Two-Factor Authentication */}
            {!userInfo.isOAuth && (
              <Card>
                <CardHeader>
                  <CardTitle>Two-Factor Authentication</CardTitle>
                  <CardDescription>
                    Add an extra layer of security to your account
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-6">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-4">
                      <div className="rounded-full bg-blue-100 p-2">
                        <Shield className="h-6 w-6 text-[#03045E]" />
                      </div>
                      <div>
                        <h3 className="text-base font-medium">
                          Two-Factor Authentication
                        </h3>
                        <p className="text-sm text-gray-500">
                          {userInfo.isTwoFactorEnabled
                            ? "Your account is protected with 2FA"
                            : "Enable 2FA for additional security"}
                        </p>
                      </div>
                    </div>
                    <Switch
                      checked={userInfo.isTwoFactorEnabled}
                      onCheckedChange={handleToggleTwoFactor}
                      disabled={isPending}
                    />
                  </div>
                  {userInfo.isTwoFactorEnabled && (
                    <div className="rounded-md bg-blue-50 p-4">
                      <div className="flex">
                        <div className="flex-shrink-0">
                          <Shield className="h-5 w-5 text-blue-400" />
                        </div>
                        <div className="ml-3">
                          <h3 className="text-sm font-medium text-blue-800">
                            Two-factor authentication is enabled
                          </h3>
                          <div className="mt-2 text-sm text-blue-700">
                            <p>
                              When you sign in, you&apos;ll need to provide a
                              verification code from your email.
                            </p>
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            )}

            {/* OAuth Account Info */}
            {userInfo.isOAuth && (
              <Card>
                <CardHeader>
                  <CardTitle>OAuth Account</CardTitle>
                  <CardDescription>
                    Your account is managed by an external provider
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="rounded-md bg-amber-50 p-4 text-amber-800">
                    <p>
                      Your account is linked to an external authentication
                      provider. Password management and two-factor
                      authentication are handled by your provider.
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </TabsContent>
      </Tabs>
      <FormError message={error} />
      <FormSuccess message={success} />
    </div>
  );
}
