// src/components/employees/EmployeePassword.tsx
'use client';

import { useState } from 'react';
import toast from 'react-hot-toast';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface EmployeePasswordProps {
  employeeId: string;
  employeeEmail: string;
  employeeName: string;
}

export default function EmployeePassword({ employeeId, employeeEmail, employeeName }: EmployeePasswordProps) {
  const [loading, setLoading] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [formData, setFormData] = useState({
    new_password: '',
    confirm_password: '',
  });
  const [errors, setErrors] = useState<Record<string, string>>({});

  const handleChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    if (errors[field]) {
      setErrors(prev => ({ ...prev, [field]: '' }));
    }
  };

  const validatePassword = (password: string): string | null => {
    if (password.length < 8) {
      return 'Password must be at least 8 characters long';
    }
    if (!/[A-Z]/.test(password)) {
      return 'Password must contain at least one uppercase letter';
    }
    if (!/[a-z]/.test(password)) {
      return 'Password must contain at least one lowercase letter';
    }
    if (!/[0-9]/.test(password)) {
      return 'Password must contain at least one number';
    }
    if (!/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
      return 'Password must contain at least one special character';
    }
    return null;
  };

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      toast.success('Password copied to clipboard');
    } catch (err) {
      toast.error(`Failed to copy password ${err instanceof Error ? err.message : 'Unknown error'}`);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    const newErrors: Record<string, string> = {};
    
    if (!formData.new_password) {
      newErrors.new_password = 'New password is required';
    } else {
      const passwordError = validatePassword(formData.new_password);
      if (passwordError) {
        newErrors.new_password = passwordError;
      }
    }
    
    if (!formData.confirm_password) {
      newErrors.confirm_password = 'Please confirm your password';
    } else if (formData.new_password !== formData.confirm_password) {
      newErrors.confirm_password = 'Passwords do not match';
    }
    
    if (Object.keys(newErrors).length > 0) {
      setErrors(newErrors);
      return;
    }
    
    setLoading(true);
    
    try {
      const res = await fetch(`/api/employees/${employeeId}/change-password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          new_password: formData.new_password,
        }),
      });
      
      const data = await res.json();
      
      if (res.ok) {
        toast.success('Password changed successfully');
        setFormData({ new_password: '', confirm_password: '' });
      } else {
        toast.error(getApiErrorMessage(data, 'Failed to change password'));
      }
    } catch (error) {
      console.error('Password change error:', error);
      toast.error('Network error — please try again');
    } finally {
      setLoading(false);
    }
  };

  const generateRandomPassword = () => {
    const length = 12;
    const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    const lowercase = 'abcdefghijklmnopqrstuvwxyz';
    const numbers = '0123456789';
    const special = '!@#$%^&*()';
    
    let password = '';
    password += uppercase[Math.floor(Math.random() * uppercase.length)];
    password += lowercase[Math.floor(Math.random() * lowercase.length)];
    password += numbers[Math.floor(Math.random() * numbers.length)];
    password += special[Math.floor(Math.random() * special.length)];
    
    const all = uppercase + lowercase + numbers + special;
    for (let i = password.length; i < length; i++) {
      password += all[Math.floor(Math.random() * all.length)];
    }
    
    // Shuffle the password
    password = password.split('').sort(() => Math.random() - 0.5).join('');
    
    setFormData(prev => ({ ...prev, new_password: password, confirm_password: password }));
    toast.success('Random password generated');
  };

  const inputStyle = {
    background: 'var(--color-surface-alt)',
    border: '1px solid var(--color-border)',
    color: 'var(--color-text)',
  };
  
  const labelStyle = {
    color: 'var(--color-text-secondary)',
  };
  
  const errorStyle = {
    color: 'var(--color-danger)',
  };

  return (
    <div className="max-w-2xl mx-auto">
      <div className="mb-6">
        <h3 className="text-lg font-semibold" style={{ color: 'var(--color-text)' }}>
          Change Password
        </h3>
        <p className="text-sm mt-1" style={{ color: 'var(--color-text-secondary)' }}>
          Change password for {employeeName} ({employeeEmail})
        </p>
      </div>
      
      <div className="rounded-lg p-6" style={{
        border: '1px solid var(--color-border)'
      }}>
        <form onSubmit={handleSubmit} className="space-y-5">
          <div>
            <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
              New Password
            </label>
            <div className="relative">
              <input
                type={showPassword ? 'text' : 'password'}
                value={formData.new_password}
                onChange={(e) => handleChange('new_password', e.target.value)}
                className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 pr-28 ${errors.new_password ? 'border-red-500' : ''}`}
                style={inputStyle}
                placeholder="Enter new password"
              />
              <div className="absolute right-2 top-1/2 -translate-y-1/2 flex gap-1">
                <button
                  type="button"
                  onClick={() => setShowPassword(!showPassword)}
                  className="p-1.5 rounded-md text-xs font-medium transition-all hover:opacity-80"
                  style={{ background: 'var(--color-surface)', color: 'var(--color-text-secondary)' }}
                  title={showPassword ? 'Hide password' : 'Show password'}
                >
                  {showPassword ? (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/>
                      <line x1="1" y1="1" x2="23" y2="23"/>
                    </svg>
                  ) : (
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
                      <circle cx="12" cy="12" r="3"/>
                    </svg>
                  )}
                </button>
                {formData.new_password && (
                  <button
                    type="button"
                    onClick={() => copyToClipboard(formData.new_password)}
                    className="p-1.5 rounded-md text-xs font-medium transition-all hover:opacity-80"
                    style={{ background: 'var(--color-surface)', color: 'var(--color-text-secondary)' }}
                    title="Copy password"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                    </svg>
                  </button>
                )}
                <button
                  type="button"
                  onClick={generateRandomPassword}
                  className="px-2 py-1.5 rounded-md text-xs font-medium transition-all hover:opacity-80"
                  style={{ background: 'var(--color-cta-light)', color: 'var(--color-cta)' }}
                  title="Generate random password"
                >
                  Generate
                </button>
              </div>
            </div>
            {errors.new_password && <p className="text-xs mt-1" style={errorStyle}>{errors.new_password}</p>}
            <div className="text-xs mt-2 space-y-1" style={{ color: 'var(--color-text-tertiary)' }}>
              <p>Password must contain:</p>
              <ul className="list-disc list-inside ml-2">
                <li>At least 8 characters</li>
                <li>One uppercase letter (A-Z)</li>
                <li>One lowercase letter (a-z)</li>
                <li>One number (0-9)</li>
                <li>One special character (!@#$%^&amp;*)</li>
              </ul>
            </div>
          </div>
          
          <div>
            <label className="block text-sm font-medium mb-1.5" style={labelStyle}>
              Confirm Password
            </label>
            <div className="relative">
              <input
                type={showPassword ? 'text' : 'password'}
                value={formData.confirm_password}
                onChange={(e) => handleChange('confirm_password', e.target.value)}
                className={`w-full px-4 py-2.5 rounded-lg text-sm outline-none transition-all focus:ring-2 focus:ring-cta/20 ${errors.confirm_password ? 'border-red-500' : ''}`}
                style={inputStyle}
                placeholder="Confirm new password"
              />
              {formData.confirm_password && (
                <button
                  type="button"
                  onClick={() => copyToClipboard(formData.confirm_password)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 p-1 rounded-md transition-all hover:opacity-80"
                  style={{ color: 'var(--color-text-tertiary)' }}
                  title="Copy password"
                >
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                  </svg>
                </button>
              )}
            </div>
            {errors.confirm_password && <p className="text-xs mt-1" style={errorStyle}>{errors.confirm_password}</p>}
          </div>
          
          <div className="flex gap-3 pt-4 border-t" style={{ borderColor: 'var(--color-border)' }}>
            <button
              type="submit"
              disabled={loading}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-90 disabled:opacity-50"
              style={{ background: 'var(--color-cta)', color: 'white' }}
            >
              {loading ? 'Changing...' : 'Change Password'}
            </button>
            <button
              type="button"
              onClick={() => {
                setFormData({ new_password: '', confirm_password: '' });
                setErrors({});
                setShowPassword(false);
              }}
              className="px-6 py-2.5 rounded-lg text-sm font-medium transition-all hover:opacity-80"
              style={{
                background: 'var(--color-surface-alt)',
                color: 'var(--color-text)',
                border: '1px solid var(--color-border)',
              }}
            >
              Clear
            </button>
          </div>
        </form>
      </div>
      
      <div className="mt-4 p-3 rounded-lg" style={{ 
        background: 'rgba(59, 130, 246, 0.1)',
        border: '1px solid var(--color-info)'
      }}>
        <div className="flex gap-2 text-xs" style={{ color: 'var(--color-text-secondary)' }}>
          <span>ℹ️</span>
          <p>When password is changed, the employee will be logged out from all devices and will need to login with the new password.</p>
        </div>
      </div>
    </div>
  );
}