import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Card } from '../components/ui/card';
import { toast } from 'sonner';
import Navbar from '../components/Navbar';
import { ArrowRight, Lock, AlertTriangle } from 'lucide-react';

const ChangePasswordRequired = () => {
  const navigate = useNavigate();
  const { user, changePassword, logout } = useAuth();
  const [loading, setLoading] = useState(false);
  const [formData, setFormData] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  });

  useEffect(() => {
    // If user is not logged in or doesn't have force_password_change, redirect
    if (!user) {
      navigate('/login');
    } else if (!user.force_password_change) {
      // User doesn't need to change password, redirect to appropriate page
      if (user.role === 'admin') {
        navigate('/admin');
      } else {
        navigate('/dashboard');
      }
    }
  }, [user, navigate]);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();

    if (formData.newPassword.length < 6) {
      toast.error('New password must be at least 6 characters');
      return;
    }

    if (formData.newPassword !== formData.confirmPassword) {
      toast.error('New passwords do not match');
      return;
    }

    setLoading(true);

    try {
      await changePassword(formData.currentPassword, formData.newPassword);
      toast.success('Password changed successfully! Redirecting...');

      // Wait a moment then redirect to dashboard
      setTimeout(() => {
        if (user.role === 'admin') {
          navigate('/admin');
        } else {
          navigate('/dashboard');
        }
      }, 1500);
    } catch (error) {
      const errorMessage = error.response?.data?.detail || 'Failed to change password';
      toast.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  if (!user || !user.force_password_change) {
    return null;
  }

  return (
    <div className="min-h-screen bg-background">
      <Navbar />

      <div className="max-w-md mx-auto px-6 py-12">
        <Card className="p-8 md:p-12 bg-background rounded-2xl border border-[var(--neutral-800)] shadow-lg">
          <div className="mb-8 text-center">
            <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#FFEBEE] mb-4">
              <AlertTriangle className="h-8 w-8 text-orange-500" />
            </div>
            <h1 className="text-4xl md:text-5xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
              Password Change Required
            </h1>
            <p className="text-lg text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              Your password was reset by an administrator. Please create a new password to continue.
            </p>
          </div>

          <form onSubmit={handleSubmit} className="space-y-6">
            <div>
              <Label htmlFor="currentPassword">Current/Temporary Password</Label>
              <Input
                id="currentPassword"
                name="currentPassword"
                type="password"
                required
                value={formData.currentPassword}
                onChange={handleInputChange}
                placeholder="Enter temporary password"
                className="h-14 rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
              />
            </div>

            <div>
              <Label htmlFor="newPassword">New Password</Label>
              <Input
                id="newPassword"
                name="newPassword"
                type="password"
                required
                value={formData.newPassword}
                onChange={handleInputChange}
                placeholder="Enter new password (min. 6 characters)"
                className="h-14 rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
              />
            </div>

            <div>
              <Label htmlFor="confirmPassword">Confirm New Password</Label>
              <Input
                id="confirmPassword"
                name="confirmPassword"
                type="password"
                required
                value={formData.confirmPassword}
                onChange={handleInputChange}
                placeholder="Re-enter new password"
                className="h-14 rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
              />
            </div>

            <div className="bg-[var(--lavender-300)] border-l-4 border-brand-purple  p-4 rounded-lg">
              <div className="flex items-start">
                <Lock className="h-5 w-5 text-brand-purple  mr-2 mt-0.5 flex-shrink-0" />
                <div className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  <p className="font-medium text-[var(--purple-ink)] mb-1">Password Requirements:</p>
                  <ul className="list-disc list-inside space-y-1">
                    <li>At least 6 characters long</li>
                    <li>Both passwords must match</li>
                  </ul>
                </div>
              </div>
            </div>

            <Button
              type="submit"
              disabled={loading}
              className="w-full bg-[var(--neutral-800)] text-[var(--purple-ink)] hover:bg-background rounded-full py-6 text-lg font-medium shadow-lg hover:scale-105 transition-transform disabled:opacity-50"
            >
              {loading ? 'Changing Password...' : 'Change Password'}
              <ArrowRight className="ml-2 h-5 w-5" />
            </Button>

            <div className="text-center pt-4 border-t border-[var(--neutral-800)]">
              <button
                type="button"
                onClick={handleLogout}
                className="text-brand-purple  hover:text-[var(--orange-light)] text-sm underline"
              >
                Logout instead
              </button>
            </div>
          </form>
        </Card>
      </div>
    </div>
  );
};

export default ChangePasswordRequired;
