import React, { useState } from 'react';
import { Lock, AlertCircle, Shield, Key, AlertTriangle, Loader2, Mail, Send, CheckCircle2, ChevronRight, RefreshCw, Eye, EyeOff } from 'lucide-react';
import { sendPasswordResetEmail, validateLogin, changeUserPassword } from '../services/whmcsService';
import { DashboardView } from '../types';
import AccountSidebar from './AccountSidebar';

interface SettingsViewProps {
  clientId: number;
  setView: (view: DashboardView) => void;
  userId?: number;
  email?: string;
}

const SettingsView: React.FC<SettingsViewProps> = ({ clientId, setView, userId, email }) => {
  const [sending, setSending] = useState(false);
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null);

  // Password Change State
  const [currentPassword, setCurrentPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPasswords, setShowPasswords] = useState(false);

  const handleSendResetEmail = async () => {
    if (!email) {
      setMessage({ type: 'error', text: 'User email not found. Please log in again.' });
      return;
    }

    setSending(true);
    setMessage(null);

    try {
      console.log(`[SettingsView] Requesting password reset email for: ${email}`);
      const result = await sendPasswordResetEmail(email);

      if (result.result === 'success') {
        setMessage({
          type: 'success',
          text: 'A password reset link has been sent to your registered email address. Please follow the instructions in the email.'
        });
      } else {
        setMessage({
          type: 'error',
          text: result.message || 'Failed to send reset email. Please try again later.'
        });
      }
    } catch (err) {
      console.error('Password Reset Error:', err);
      setMessage({ type: 'error', text: 'An unexpected error occurred. Please try again.' });
    } finally {
      setSending(false);
    }
  };

  const handleChangePassword = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!email) {
      setMessage({ type: 'error', text: 'User identity not fully established. Please re-login.' });
      return;
    }

    if (newPassword !== confirmPassword) {
      setMessage({ type: 'error', text: 'New passwords do not match.' });
      return;
    }

    if (newPassword.length < 6) {
      setMessage({ type: 'error', text: 'New password must be at least 6 characters long.' });
      return;
    }

    setSending(true);
    setMessage(null);

    try {
      console.log(`[SettingsView] Verifying old password for: ${email}...`);

      // 1. Verify old password using validateLogin
      const authCheck = await validateLogin(email, currentPassword);

      if (authCheck.result !== 'success') {
        setMessage({
          type: 'error',
          text: 'The current password you entered is incorrect. Please try again.'
        });
        setSending(false);
        return;
      }

      console.log(`[SettingsView] Auth success. Updating password...`);

      // 2. Change password
      const result = await changeUserPassword(clientId, newPassword, userId, email);

      if (result.result === 'success') {
        setMessage({
          type: 'success',
          text: 'Your password has been changed successfully! Please use your new password for future logins.'
        });
        // Clear fields
        setCurrentPassword('');
        setNewPassword('');
        setConfirmPassword('');
      } else {
        setMessage({
          type: 'error',
          text: result.message || 'Failed to update password. Your backend may have API restrictions.'
        });
      }
    } catch (err) {
      console.error('Password Change Error:', err);
      setMessage({ type: 'error', text: 'An unexpected security error occurred. Please try again.' });
    } finally {
      setSending(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#F8FAFC]">
      {/* Professional Header Section */}
      <div className="bg-white border-b border-slate-200">
        <div className="max-w-7xl mx-auto px-6 py-8 relative z-10">
          <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
            <div className="space-y-1">
              <h1 className="text-2xl font-bold text-slate-900 tracking-tight text-center md:text-left">
                Account <span className="text-blue-600">Security</span>
              </h1>
              <div className="flex items-center justify-center md:justify-start gap-2 text-[11px] text-slate-400 font-bold uppercase tracking-wider">
                <span className="hover:text-blue-600 transition-colors cursor-pointer" onClick={() => setView(DashboardView.OVERVIEW)}>Client Area</span>
                <ChevronRight size={10} className="text-slate-300" />
                <span className="text-slate-500">Account Settings</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-6 py-10">
        <div className="flex flex-col lg:flex-row gap-10">
          {/* Sidebar Navigator */}
          <div className="w-full lg:w-64 flex-shrink-0">
            <AccountSidebar clientId={clientId} currentView={DashboardView.SETTINGS} setView={setView} />
          </div>

          {/* Main Content Area */}
          <div className="flex-1 space-y-8">
            <section className="bg-white border border-slate-200 rounded-xl p-6 shadow-sm">
              <div className="flex items-center gap-3 mb-6">
                <div className="w-10 h-10 bg-blue-50 rounded-lg flex items-center justify-center text-blue-600">
                  <Shield size={20} />
                </div>
                <div>
                  <h2 className="text-base font-bold text-slate-800">Security Status</h2>
                  <p className="text-slate-400 text-[11px] font-bold uppercase tracking-wider">Account access status</p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div className="flex items-center justify-between p-3 bg-emerald-50 rounded-xl border border-emerald-100">
                    <div className="flex items-center gap-3">
                      <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
                      <span className="text-xs font-bold text-emerald-700 uppercase tracking-wide">Account Active</span>
                    </div>
                    <CheckCircle2 size={16} className="text-emerald-500" />
                  </div>
                  <div className="p-4 bg-slate-50 rounded-xl border border-slate-100">
                    <p className="text-xs text-slate-500 leading-relaxed font-medium">
                      Your account is protected with enterprise-grade encryption. To maintain security, we recommend regular password updates.
                    </p>
                  </div>
                </div>

                <div className="bg-slate-50 p-6 rounded-xl border border-slate-200/60 h-full">
                  <h3 className="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4 flex items-center gap-2">
                    <AlertCircle size={14} />
                    Account Information
                  </h3>
                  <div className="space-y-3 text-[11px] font-mono text-slate-500">
                    <div className="flex justify-between border-b border-slate-200 pb-2">
                      <span>Client ID</span>
                      <span className="font-bold text-slate-700">{clientId}</span>
                    </div>
                    <div className="flex justify-between">
                      <span>Registered Email</span>
                      <span className={`font-bold ${email ? 'text-slate-700' : 'text-red-500'}`}>
                        {email || 'Not Detected'}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </section>

            <section className="bg-white border border-slate-200 rounded-xl p-8 shadow-sm relative overflow-hidden">
              {/* Design Element */}
              <div className="absolute top-0 right-0 -mr-16 -mt-16 w-64 h-64 bg-blue-50/50 rounded-full blur-3xl -z-10"></div>

              <div className="relative">
                <h2 className="text-xl font-bold text-slate-900 mb-2 flex items-center gap-2">
                  <Key size={20} className="text-blue-600" />
                  Update Password
                </h2>
                <p className="text-slate-500 text-xs font-medium mb-8">
                  Update your account access credentials directly. Ensure you use a strong password.
                </p>

                {message && (
                  <div className={`p-4 mb-8 rounded-xl flex items-start gap-4 border animate-in slide-in-from-top-2 duration-300 ${message.type === 'success'
                    ? 'bg-emerald-50 text-emerald-700 border-emerald-100 shadow-sm shadow-emerald-200/40'
                    : 'bg-red-50 text-red-600 border-red-100'
                    }`}>
                    <div className={`p-2 rounded-lg mt-0.5 ${message.type === 'success' ? 'bg-emerald-500/10' : 'bg-red-500/10'}`}>
                      {message.type === 'success' ? <CheckCircle2 size={18} /> : <AlertTriangle size={18} />}
                    </div>
                    <div className="space-y-1">
                      <p className="font-bold text-sm leading-tight">{message.type === 'success' ? 'Success!' : 'Error'}</p>
                      <p className="text-[11px] font-medium opacity-90">{message.text}</p>
                    </div>
                  </div>
                )}

                <form onSubmit={handleChangePassword} className="space-y-6">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider ml-1">Current Password</label>
                      <div className="relative">
                        <input
                          type={showPasswords ? "text" : "password"}
                          value={currentPassword}
                          onChange={(e) => setCurrentPassword(e.target.value)}
                          className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-slate-700 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all pr-12"
                          placeholder="Verify current password"
                          required
                        />
                        <button
                          type="button"
                          onClick={() => setShowPasswords(!showPasswords)}
                          className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-slate-400 hover:text-slate-600 transition-colors"
                        >
                          {showPasswords ? <EyeOff size={16} /> : <Eye size={16} />}
                        </button>
                      </div>
                    </div>

                    <div className="hidden md:block"></div>

                    <div className="space-y-2">
                      <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider ml-1">New Password</label>
                      <input
                        type={showPasswords ? "text" : "password"}
                        value={newPassword}
                        onChange={(e) => setNewPassword(e.target.value)}
                        className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-slate-700 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all"
                        placeholder="Enter new password"
                        required
                      />
                    </div>

                    <div className="space-y-2">
                      <label className="text-[11px] font-bold text-slate-400 uppercase tracking-wider ml-1">Confirm New Password</label>
                      <input
                        type={showPasswords ? "text" : "password"}
                        value={confirmPassword}
                        onChange={(e) => setConfirmPassword(e.target.value)}
                        className="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-slate-700 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none transition-all"
                        placeholder="Confirm new password"
                        required
                      />
                    </div>
                  </div>

                  <div className="pt-4 flex flex-col md:flex-row items-center gap-4">
                    <button
                      type="submit"
                      disabled={sending || !currentPassword || !newPassword || !confirmPassword}
                      className="w-full md:w-auto px-8 py-3 bg-slate-900 hover:bg-blue-600 text-white rounded-xl font-bold text-[10px] uppercase tracking-widest shadow-lg shadow-slate-200/50 transition-all flex items-center justify-center gap-3 hover:shadow-blue-500/30 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed group"
                    >
                      {sending ? (
                        <>
                          <RefreshCw size={14} className="animate-spin" />
                          Processing...
                        </>
                      ) : (
                        <>
                          <CheckCircle2 size={14} className="group-hover:scale-110 transition-transform" />
                          Update Password Now
                        </>
                      )}
                    </button>

                    <button
                      type="button"
                      onClick={handleSendResetEmail}
                      disabled={sending}
                      className="text-[10px] font-bold text-blue-600 hover:text-blue-700 uppercase tracking-widest px-4 py-2 hover:bg-blue-50 rounded-lg transition-all"
                    >
                      Forgot password? Reset via Email
                    </button>
                  </div>
                </form>

                <div className="mt-8 flex items-start gap-3 p-4 bg-amber-50 rounded-xl border border-amber-100">
                  <AlertCircle size={16} className="text-amber-600 mt-0.5 shrink-0" />
                  <p className="text-[10px] text-amber-700 font-bold leading-relaxed">
                    Security Tip: Use a combination of uppercase, lowercase, numbers, and specialized characters to ensure maximum account protection.
                  </p>
                </div>
              </div>
            </section>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SettingsView;
