"use client";

import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormDescription,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { useToast } from "@/hooks/use-toast";
import { handleUpdateOwnCredentials } from "@/lib/actions";
import { useTransition } from "react";
import { Loader2 } from "lucide-react";

const formSchema = z.object({
  newPassword: z.string().min(6, "يجب أن تحتوي كلمة المرور على 6 أحرف على الأقل.").optional().or(z.literal('')),
});

type Translation = {
  newPassword: string;
  updatePasswordButton: string;
}

export function ChangePasswordForm({ t, username, formId }: { t: Translation; username: string; formId?: string }) {
  const [isPending, startTransition] = useTransition();
  const { toast } = useToast();
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      newPassword: "",
    },
  });

  async function onSubmit(values: z.infer<typeof formSchema>) {
    startTransition(async () => {
      const result = await handleUpdateOwnCredentials(values);
      if (result?.error) {
        toast({
          title: "فشل التحديث",
          description: result.error,
          variant: "destructive",
        });
      } else {
        toast({
          title: "تم الحفظ",
          description: "تم تحديث بيانات تسجيل الدخول بنجاح.",
        });
        form.reset();
      }
    });
  }

  return (
    <Form {...form}>
      <form id={formId} onSubmit={form.handleSubmit(onSubmit)} className="space-y-6 max-w-lg">
        <div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4 space-y-4">
          <h3 className="font-semibold text-sm">بيانات تسجيل الدخول</h3>
          <FormItem>
            <FormLabel>اسم المستخدم</FormLabel>
            <FormControl>
              <Input value={username} readOnly disabled className="bg-gray-100" />
            </FormControl>
          </FormItem>
        <FormField
          control={form.control}
          name="newPassword"
          render={({ field }) => (
            <FormItem>
              <FormLabel>كلمة المرور الجديدة (اتركه فارغًا للاحتفاظ بكلمة المرور الحالية.)</FormLabel>
              <FormControl>
                <Input type="password" placeholder="••••••••" {...field} />
              </FormControl>
              <FormDescription>{t.newPassword}</FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
        </div>
      </form>
    </Form>
  );
}
