'use client';

import { useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { AlertCircle, Eye, EyeOff, LoaderCircleIcon } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { toast } from 'sonner';
import { apiClient } from '@/lib/api';
import { Alert, AlertIcon, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { Input } from '@/components/ui/input';
import {
  ChangePasswordSchemaType,
  getChangePasswordSchema,
} from '@/app/(auth)/forms/change-password-schema';

export default function ChangePasswordForm() {
  const [passwordVisible, setPasswordVisible] = useState({
    current: false,
    new: false,
    confirm: false,
  });
  const [isProcessing, setIsProcessing] = useState(false);
  const { t } = useTranslation();

  const form = useForm<ChangePasswordSchemaType>({
    resolver: zodResolver(getChangePasswordSchema(t)),
    defaultValues: {
      currentPassword: '',
      newPassword: '',
      confirmPassword: '',
    },
  });

  async function onSubmit(values: ChangePasswordSchemaType) {
    setIsProcessing(true);

    try {
      await apiClient.post(
        '/contractor/change-password',
        {
          current_password: values.currentPassword,
          password: values.newPassword,
          password_confirmation: values.confirmPassword,
        },
        { requireAuth: true },
      );

      toast.success(
        t('profile.messages.success') || 'Password updated successfully!',
      );
      form.reset();
    } catch (error: any) {
      console.error('Change password error:', error);
      toast.error(
        error.message ||
          t('profile.messages.error') ||
          'Failed to change password',
      );
    } finally {
      setIsProcessing(false);
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>{t('profile.changePassword')}</CardTitle>
      </CardHeader>
      <CardContent>
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="w-full space-y-5"
          >
            {/* Password Fields */}

            {/* Current Password */}
            <FormField
              control={form.control}
              name="currentPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('profile.labels.currentPassword')}</FormLabel>
                  <div className="relative">
                    <FormControl>
                      <Input
                        type={passwordVisible.current ? 'text' : 'password'}
                        autoComplete="current-password"
                        placeholder={t('profile.placeholders.currentPassword')}
                        {...field}
                      />
                    </FormControl>
                    <Button
                      type="button"
                      variant="ghost"
                      mode="icon"
                      size="sm"
                      onClick={() =>
                        setPasswordVisible((p) => ({
                          ...p,
                          current: !p.current,
                        }))
                      }
                      className="absolute end-0 top-1/2 -translate-y-1/2 h-7 w-7 me-1.5"
                    >
                      {passwordVisible.current ? <EyeOff /> : <Eye />}
                    </Button>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* New Password */}
            <FormField
              control={form.control}
              name="newPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('profile.labels.newPassowed')}</FormLabel>
                  <div className="relative">
                    <FormControl>
                      <Input
                        type={passwordVisible.new ? 'text' : 'password'}
                        autoComplete="new-password"
                        placeholder={t('profile.placeholders.newPassowed')}
                        {...field}
                      />
                    </FormControl>
                    <Button
                      type="button"
                      variant="ghost"
                      mode="icon"
                      size="sm"
                      onClick={() =>
                        setPasswordVisible((p) => ({ ...p, new: !p.new }))
                      }
                      className="absolute end-0 top-1/2 -translate-y-1/2 h-7 w-7 me-1.5"
                    >
                      {passwordVisible.new ? <EyeOff /> : <Eye />}
                    </Button>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            {/* Confirm Password */}
            <FormField
              control={form.control}
              name="confirmPassword"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t('profile.labels.confirmPassword')}</FormLabel>
                  <div className="relative">
                    <FormControl>
                      <Input
                        autoComplete="new-password"
                        type={passwordVisible.confirm ? 'text' : 'password'}
                        placeholder={t('profile.placeholders.confirmPassword')}
                        {...field}
                      />
                    </FormControl>
                    <Button
                      type="button"
                      variant="ghost"
                      mode="icon"
                      size="sm"
                      onClick={() =>
                        setPasswordVisible((p) => ({
                          ...p,
                          confirm: !p.confirm,
                        }))
                      }
                      className="absolute end-0 top-1/2 -translate-y-1/2 h-7 w-7 me-1.5"
                    >
                      {passwordVisible.confirm ? <EyeOff /> : <Eye />}
                    </Button>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button type="submit" disabled={isProcessing} className="w-full">
              {isProcessing && (
                <LoaderCircleIcon className="size-4 animate-spin mr-2" />
              )}
              {t('profile.changePassword')}
            </Button>
          </form>
        </Form>
      </CardContent>
    </Card>
  );
}
