'use client';

import { useState } from 'react';
import { useForm } from 'react-hook-form';
import toast from 'react-hot-toast';
import { Loader2, User, Mail, Lock, Eye, EyeOff } from 'lucide-react';
import { profileApi } from '@/lib/api';
import { useAuth } from '@/lib/auth';

export default function ProfilePage() {
  const { user, refreshUser } = useAuth();
  const [isUpdating, setIsUpdating] = useState(false);
  const [isChangingPw, setIsChangingPw] = useState(false);
  const [showCurrentPw, setShowCurrentPw] = useState(false);
  const [showNewPw, setShowNewPw] = useState(false);

  const profileForm = useForm({
    defaultValues: {
      display_name: user?.display_name || '',
      email: user?.email || '',
    },
  });

  const pwForm = useForm({
    defaultValues: {
      current_password: '',
      new_password: '',
      new_password_confirmation: '',
    },
  });

  const handleProfileUpdate = profileForm.handleSubmit(async (data) => {
    setIsUpdating(true);
    try {
      await profileApi.update(data);
      await refreshUser();
      toast.success('Profile updated');
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to update profile');
    } finally {
      setIsUpdating(false);
    }
  });

  const handlePasswordChange = pwForm.handleSubmit(async (data) => {
    if (data.new_password !== data.new_password_confirmation) {
      pwForm.setError('new_password_confirmation', { message: 'Passwords must match' });
      return;
    }
    setIsChangingPw(true);
    try {
      await profileApi.changePassword(data);
      toast.success('Password changed');
      pwForm.reset();
    } catch (err: any) {
      toast.error(err.response?.data?.message || 'Failed to change password');
    } finally {
      setIsChangingPw(false);
    }
  });

  if (!user) return null;

  const roleColors: Record<string, string> = {
    'master-admin': 'text-purple-400 bg-purple-400/10',
    'admin':        'text-ts-accent bg-ts-accent/10',
    'operator':     'text-green-400 bg-green-400/10',
  };

  return (
    <div className="max-w-2xl">
      <h1 className="text-xl font-semibold mb-6">My Profile</h1>

      {/* Identity card */}
      <div className="ts-card p-6 mb-5 flex items-center gap-5">
        <div className="w-16 h-16 rounded-2xl bg-ts-accent/10 border border-ts-accent/20 flex items-center justify-center shrink-0">
          <span className="text-2xl font-bold text-ts-accent">
            {(user.display_name || user.name)?.[0]?.toUpperCase()}
          </span>
        </div>
        <div>
          <p className="text-lg font-semibold text-ts-text">{user.display_name || user.name}</p>
          <p className="text-sm text-ts-muted">@{user.username}</p>
          <span className={`inline-block text-xs font-medium px-2 py-0.5 rounded mt-1 ${roleColors[user.role]}`}>
            {user.role}
          </span>
        </div>
      </div>

      {/* Profile form */}
      <div className="ts-card p-6 mb-5">
        <h2 className="font-medium mb-4 flex items-center gap-2">
          <User size={16} className="text-ts-accent" />
          Personal Information
        </h2>
        <form onSubmit={handleProfileUpdate} className="space-y-4">
          <div>
            <label className="ts-label">Username</label>
            <input
              value={user.username}
              disabled
              className="ts-input opacity-50 cursor-not-allowed"
            />
            <p className="text-xs text-ts-muted mt-1">Username cannot be changed</p>
          </div>

          {/* Operators can only change name */}
          {user.role === 'operator' ? (
            <div>
              <label className="ts-label">Display Name</label>
              <input {...profileForm.register('display_name')} className="ts-input" />
            </div>
          ) : (
            <>
              <div>
                <label className="ts-label">Display Name</label>
                <input {...profileForm.register('display_name')} className="ts-input" />
              </div>
              <div>
                <label className="ts-label">Email</label>
                <input {...profileForm.register('email')} type="email" className="ts-input" />
              </div>
            </>
          )}

          <button type="submit" disabled={isUpdating} className="ts-btn-primary flex items-center gap-2">
            {isUpdating && <Loader2 size={15} className="animate-spin" />}
            Save Changes
          </button>
        </form>
      </div>

      {/* Password */}
      <div className="ts-card p-6">
        <h2 className="font-medium mb-4 flex items-center gap-2">
          <Lock size={16} className="text-ts-accent" />
          Change Password
        </h2>
        <form onSubmit={handlePasswordChange} className="space-y-4">
          <div>
            <label className="ts-label">Current Password</label>
            <div className="relative">
              <input
                {...pwForm.register('current_password')}
                type={showCurrentPw ? 'text' : 'password'}
                className="ts-input pr-10"
              />
              <button type="button" onClick={() => setShowCurrentPw(!showCurrentPw)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-ts-muted hover:text-ts-text">
                {showCurrentPw ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
          </div>
          <div>
            <label className="ts-label">New Password</label>
            <div className="relative">
              <input
                {...pwForm.register('new_password')}
                type={showNewPw ? 'text' : 'password'}
                className="ts-input pr-10"
              />
              <button type="button" onClick={() => setShowNewPw(!showNewPw)}
                className="absolute right-3 top-1/2 -translate-y-1/2 text-ts-muted hover:text-ts-text">
                {showNewPw ? <EyeOff size={15} /> : <Eye size={15} />}
              </button>
            </div>
            <p className="text-xs text-ts-muted mt-1">Upper, lower, digit, special character required</p>
          </div>
          <div>
            <label className="ts-label">Confirm New Password</label>
            <input {...pwForm.register('new_password_confirmation')} type="password" className="ts-input" />
          </div>
          <button type="submit" disabled={isChangingPw} className="ts-btn-primary flex items-center gap-2">
            {isChangingPw && <Loader2 size={15} className="animate-spin" />}
            Change Password
          </button>
        </form>
      </div>
    </div>
  );
}
