import { Component, createSignal, createMemo } from 'solid-js';
import { createMutation } from '@tanstack/solid-query';
import { trpcClient } from '../../lib/api/trpc-client';

export interface PasswordResetProps {
  onSuccess?: (message: string) => void;
  onNavigateSignIn?: () => void;
  mode?: 'request' | 'confirm';
  token?: string;
  email?: string;
}

export const PasswordReset: Component<PasswordResetProps> = (props) => {
  const [email, setEmail] = createSignal(props.email || '');
  const [newPassword, setNewPassword] = createSignal('');
  const [confirmPassword, setConfirmPassword] = createSignal('');
  const [showPassword, setShowPassword] = createSignal(false);

  const isConfirmMode = props.mode === 'confirm';

  const passwordsMatch = createMemo(() => {
    return newPassword() === confirmPassword() && newPassword().length > 0;
  });

  const requestResetMutation = createMutation({
    mutationFn: async (input: { email: string }) => {
      const result = await trpcClient.auth.requestPasswordReset.mutate(input);
      return result as { message: string };
    },
    onSuccess: (data) => {
      props.onSuccess?.(data.message);
    },
  });

  const confirmResetMutation = createMutation({
    mutationFn: async (input: { token: string; newPassword: string }) => {
      const result = await trpcClient.auth.confirmPasswordReset.mutate(input);
      return result as { message: string };
    },
    onSuccess: (data) => {
      props.onSuccess?.(data.message);
    },
  });

  const handleSubmit = (e: Event) => {
    e.preventDefault();
    if (isConfirmMode && !passwordsMatch()) return;

    if (isConfirmMode) {
      confirmResetMutation.mutate({
        token: props.token!,
        newPassword: newPassword(),
      });
    } else {
      requestResetMutation.mutate({ email: email() });
    }
  };

  return (
    <div class="auth-container">
      <div class="auth-card">
        <h2 class="auth-title">
          {isConfirmMode ? 'Reset Password' : 'Forgot Password'}
        </h2>
        <p class="auth-subtitle">
          {isConfirmMode
            ? 'Enter your new password'
            : "We'll send you a reset link"}
        </p>

        <form onSubmit={handleSubmit} class="auth-form">
          {!isConfirmMode && (
            <div class="form-group">
              <label for="email">Email</label>
              <input
                id="email"
                type="email"
                value={email()}
                onInput={(e) => setEmail(e.currentTarget.value)}
                placeholder="Enter your email"
                required
                class="form-input"
              />
            </div>
          )}

          {isConfirmMode && (
            <>
              <div class="form-group">
                <label for="newPassword">New Password</label>
                <div class="password-input-wrapper">
                  <input
                    id="newPassword"
                    type={showPassword() ? 'text' : 'password'}
                    value={newPassword()}
                    onInput={(e) => setNewPassword(e.currentTarget.value)}
                    placeholder="Enter new password"
                    required
                    class="form-input"
                    minlength="8"
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword())}
                    class="password-toggle"
                    aria-label={showPassword() ? 'Hide password' : 'Show password'}
                  >
                    {showPassword() ? 'Hide' : 'Show'}
                  </button>
                </div>
              </div>

              <div class="form-group">
                <label for="confirmPassword">Confirm New Password</label>
                <input
                  id="confirmPassword"
                  type={showPassword() ? 'text' : 'password'}
                  value={confirmPassword()}
                  onInput={(e) => setConfirmPassword(e.currentTarget.value)}
                  placeholder="Confirm your new password"
                  required
                  class="form-input"
                />
              </div>

              {!passwordsMatch() && newPassword().length > 0 && (
                <div class="error-message" role="alert">
                  Passwords do not match
                </div>
              )}
            </>
          )}

          {(requestResetMutation.error || confirmResetMutation.error) && (
            <div class="error-message" role="alert">
              {(requestResetMutation.error || confirmResetMutation.error)?.message}
            </div>
          )}

          <button
            type="submit"
            disabled={
              (isConfirmMode
                ? confirmResetMutation.isPending || !passwordsMatch()
                : requestResetMutation.isPending)
            }
            class="auth-btn-primary"
          >
            {isConfirmMode
              ? confirmResetMutation.isPending
                ? 'Resetting password...'
                : 'Reset Password'
              : requestResetMutation.isPending
              ? 'Sending link...'
              : 'Send Reset Link'}
          </button>
        </form>

        <div class="auth-footer">
          <p>
            Remember your password?{' '}
            <button
              type="button"
              onClick={props.onNavigateSignIn}
              class="auth-link"
            >
              Sign in
            </button>
          </p>
        </div>
      </div>
    </div>
  );
};
