'use client'

import { useState } from 'react'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '../ui/card'
import { Loader2 } from 'lucide-react'

export interface ChangePasswordFormProps {
  onSubmit: (values: {
    old_password: string
    new_password: string
  }) => Promise<void>
  /** Called after a successful password change (e.g. to sign out) */
  onSuccess?: () => void
  disabled?: boolean
}

export function ChangePasswordForm({ onSubmit, onSuccess, disabled }: ChangePasswordFormProps) {
  const [oldPassword, setOldPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [success, setSuccess] = useState(false)

  const isValid = oldPassword.length > 0 && newPassword.length >= 8

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    setSuccess(false)

    setSaving(true)

    try {
      await onSubmit({
        old_password: oldPassword,
        new_password: newPassword,
      })
      setSuccess(true)
      setOldPassword('')
      setNewPassword('')
      onSuccess?.()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to change password')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Change password</CardTitle>
        <CardDescription>
          Update your password. You will need to sign in again after changing it.
        </CardDescription>
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="cp-old-password">Current password</Label>
            <Input
              id="cp-old-password"
              type="password"
              value={oldPassword}
              onChange={(e) => setOldPassword(e.target.value)}
              disabled={disabled || saving}
              autoComplete="current-password"
            />
          </div>

          <div className="space-y-2">
            <Label htmlFor="cp-new-password">New password</Label>
            <Input
              id="cp-new-password"
              type="password"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              disabled={disabled || saving}
              autoComplete="new-password"
            />
            {newPassword.length > 0 && newPassword.length < 8 && (
              <p className="text-xs text-muted-foreground">
                Must be at least 8 characters.
              </p>
            )}
          </div>

          {error && (
            <p className="text-sm text-destructive">{error}</p>
          )}

          {success && (
            <p className="text-sm text-green-600">Password changed successfully.</p>
          )}

          <Button type="submit" disabled={disabled || saving || !isValid}>
            {saving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            Change password
          </Button>
        </form>
      </CardContent>
    </Card>
  )
}
