import React, { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import api from '../utils/api';
import { Card } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Label } from '../components/ui/label';
import { Alert, AlertDescription } from '../components/ui/alert';
import { Badge } from '../components/ui/badge';
import { toast } from 'sonner';
import { Loader2, Mail, Shield, CheckCircle, XCircle, Calendar } from 'lucide-react';

const AcceptInvitation = () => {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { login } = useAuth();
  const [token, setToken] = useState(null);
  const [invitation, setInvitation] = useState(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [success, setSuccess] = useState(false);
  const [successUser, setSuccessUser] = useState(null);
  const [error, setError] = useState(null);
  const [formData, setFormData] = useState({
    password: '',
    confirmPassword: '',
    first_name: '',
    last_name: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    zipcode: '',
    date_of_birth: ''
  });
  const [formErrors, setFormErrors] = useState({});

  useEffect(() => {
    const invitationToken = searchParams.get('token');
    if (!invitationToken) {
      setError('Invalid invitation link. No token provided.');
      setLoading(false);
      return;
    }

    setToken(invitationToken);
    verifyInvitation(invitationToken);
  }, [searchParams]);

  const verifyInvitation = async (invitationToken) => {
    try {
      const response = await api.get(`/invitations/verify/${invitationToken}`);
      setInvitation(response.data);

      // Pre-fill form with invitation data
      setFormData(prev => ({
        ...prev,
        first_name: response.data.first_name || '',
        last_name: response.data.last_name || '',
        phone: response.data.phone || ''
      }));

      setLoading(false);
    } catch (error) {
      setError(error.response?.data?.detail || 'Invalid or expired invitation token');
      setLoading(false);
    }
  };

  const handleChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // Clear error when user starts typing
    if (formErrors[field]) {
      setFormErrors(prev => ({ ...prev, [field]: null }));
    }
  };

  const validate = () => {
    const newErrors = {};

    if (!formData.password || formData.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
    }

    if (formData.password !== formData.confirmPassword) {
      newErrors.confirmPassword = 'Passwords do not match';
    }

    if (!formData.first_name) {
      newErrors.first_name = 'First name is required';
    }

    if (!formData.last_name) {
      newErrors.last_name = 'Last name is required';
    }

    if (!formData.phone) {
      newErrors.phone = 'Phone is required';
    }

    setFormErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    if (!validate()) {
      return;
    }

    setSubmitting(true);

    try {
      // Prepare payload
      const payload = {
        token,
        password: formData.password,
        first_name: formData.first_name,
        last_name: formData.last_name,
        phone: formData.phone
      };

      // Add optional fields if provided
      if (formData.address) payload.address = formData.address;
      if (formData.city) payload.city = formData.city;
      if (formData.state) payload.state = formData.state;
      if (formData.zipcode) payload.zipcode = formData.zipcode;
      if (formData.date_of_birth) payload.date_of_birth = formData.date_of_birth;

      // Accept invitation
      const response = await api.post('/invitations/accept', payload);

      // Auto-login with returned token
      const { access_token, user } = response.data;
      localStorage.setItem('token', access_token);

      // Call login to update auth context
      if (login) {
        await login(invitation.email, formData.password);
      }

      // Show success state
      setSuccessUser(user);
      setSuccess(true);

      // Auto-redirect after 3 seconds
      setTimeout(() => {
        if (user.role === 'admin' || user.role === 'superadmin') {
          navigate('/admin');
        } else {
          navigate('/dashboard');
        }
      }, 3000);
    } catch (error) {
      const errorMessage = error.response?.data?.detail || 'Failed to accept invitation';
      toast.error(errorMessage);
    } finally {
      setSubmitting(false);
    }
  };

  const getRoleBadge = (role) => {
    const config = {
      superadmin: { label: 'Superadmin', className: 'bg-brand-purple  text-white' },
      admin: { label: 'Admin', className: 'bg-[var(--green-light)] text-white' },
      member: { label: 'Member', className: 'bg-[var(--neutral-800)] text-[var(--purple-ink)]' }
    };

    const roleConfig = config[role] || { label: role, className: 'bg-gray-500 text-white' };
    return (
      <Badge className={`${roleConfig.className} px-4 py-2 rounded-full text-sm`}>
        <Shield className="h-4 w-4 mr-2 inline" />
        {roleConfig.label}
      </Badge>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-[var(--lavender-700)] to-white flex items-center justify-center p-4">
        <Card className="w-full max-w-md p-12 bg-background rounded-2xl border border-[var(--neutral-800)] text-center">
          <Loader2 className="h-12 w-12 text-brand-purple  mx-auto mb-4 animate-spin" />
          <p className="text-lg text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
            Verifying your invitation...
          </p>
        </Card>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-[var(--lavender-700)] to-white flex items-center justify-center p-4">
        <Card className="w-full max-w-md p-12 bg-background rounded-2xl border border-[var(--neutral-800)] text-center">
          <XCircle className="h-16 w-16 text-red-500 mx-auto mb-6" />
          <h1 className="text-2xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Invalid Invitation
          </h1>
          <p className="text-brand-purple  mb-8" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            {error}
          </p>
          <Button
            onClick={() => navigate('/login')}
            className="rounded-xl bg-brand-purple  hover:bg-[var(--purple-ink)] text-white"
          >
            Go to Login
          </Button>
        </Card>
      </div>
    );
  }

  if (success) {
    const redirectPath = successUser?.role === 'admin' || successUser?.role === 'superadmin' ? '/admin' : '/dashboard';

    return (
      <div className="min-h-screen bg-gradient-to-br from-[var(--lavender-700)] to-white flex items-center justify-center p-4">
        <Card className="w-full max-w-2xl p-12 bg-background rounded-2xl border border-[var(--neutral-800)] text-center">
          {/* Success Animation */}
          <div className="mb-8">
            <div className="h-24 w-24 mx-auto rounded-full bg-gradient-to-br from-[var(--green-light)] to-[var(--green-fern)] flex items-center justify-center animate-bounce">
              <CheckCircle className="h-12 w-12 text-white" />
            </div>
          </div>

          {/* Success Message */}
          <h1 className="text-4xl font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
            Welcome to LOAF! 🎉
          </h1>
          <p className="text-xl text-brand-purple  mb-8" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Your account has been created successfully.
          </p>

          {/* User Info Card */}
          <div className="mb-8 p-6 bg-gradient-to-r from-[var(--neutral-800)] to-[var(--lavender-700)] rounded-xl">
            <div className="grid md:grid-cols-2 gap-4 text-left">
              <div>
                <p className="text-sm text-brand-purple  mb-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Name
                </p>
                <p className="font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {successUser?.first_name} {successUser?.last_name}
                </p>
              </div>
              <div>
                <p className="text-sm text-brand-purple  mb-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Email
                </p>
                <p className="font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                  {successUser?.email}
                </p>
              </div>
              <div>
                <p className="text-sm text-brand-purple  mb-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Role
                </p>
                <div>{getRoleBadge(successUser?.role)}</div>
              </div>
              <div>
                <p className="text-sm text-brand-purple  mb-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                  Status
                </p>
                <Badge className="bg-[var(--green-light)] text-white px-4 py-2 rounded-full text-sm">
                  {successUser?.status}
                </Badge>
              </div>
            </div>
          </div>

          {/* Redirect Info */}
          <div className="mb-8 p-4 bg-blue-50 border border-blue-200 rounded-xl">
            <p className="text-sm text-blue-800" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
              <Loader2 className="h-4 w-4 inline mr-2 animate-spin" />
              Redirecting you to your dashboard in 3 seconds...
            </p>
          </div>

          {/* Manual Continue Button */}
          <Button
            onClick={() => navigate(redirectPath)}
            className="w-full h-14 rounded-xl bg-gradient-to-r from-[var(--green-light)] to-[var(--green-fern)] hover:from-[var(--green-fern)] hover:to-[var(--green-sage)] text-white text-lg font-semibold"
          >
            Continue to Dashboard
          </Button>
        </Card>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-[var(--lavender-700)] to-white flex items-center justify-center p-4">
      <Card className="w-full max-w-3xl p-8 md:p-12 bg-background rounded-2xl border border-[var(--neutral-800)]">
        {/* Header */}
        <div className="text-center mb-8">
          <div className="flex justify-center mb-4">
            <div className="h-16 w-16 rounded-full bg-gradient-to-br from-brand-purple  to-[var(--purple-ink)] flex items-center justify-center">
              <Mail className="h-8 w-8 text-white" />
            </div>
          </div>
          <h1 className="text-3xl md:text-4xl font-semibold text-[var(--purple-ink)] mb-3" style={{ fontFamily: "'Inter', sans-serif" }}>
            Welcome to LOAF!
          </h1>
          <p className="text-lg text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Complete your profile to accept the invitation
          </p>
        </div>

        {/* Invitation Details */}
        <div className="mb-8 p-6 bg-gradient-to-r from-[var(--neutral-800)] to-[var(--lavender-700)] rounded-xl">
          <div className="grid md:grid-cols-2 gap-4 text-sm">
            <div>
              <p className="text-brand-purple  mb-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Email Address
              </p>
              <p className="font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                {invitation?.email}
              </p>
            </div>
            <div>
              <p className="text-brand-purple  mb-1" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                Role
              </p>
              <div>{getRoleBadge(invitation?.role)}</div>
            </div>
            <div className="md:col-span-2">
              <p className="text-brand-purple  mb-1 flex items-center gap-2" style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
                <Calendar className="h-4 w-4" />
                Invitation Expires
              </p>
              <p className="font-semibold text-[var(--purple-ink)]" style={{ fontFamily: "'Inter', sans-serif" }}>
                {invitation?.expires_at ? new Date(invitation.expires_at).toLocaleString() : 'N/A'}
              </p>
            </div>
          </div>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit}>
          <div className="grid gap-6">
            {/* Password Fields */}
            <div className="grid md:grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="password" className="text-[var(--purple-ink)]">
                  Password <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="password"
                  type="password"
                  value={formData.password}
                  onChange={(e) => handleChange('password', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="Minimum 8 characters"
                />
                {formErrors.password && (
                  <p className="text-sm text-red-500">{formErrors.password}</p>
                )}
              </div>

              <div className="grid gap-2">
                <Label htmlFor="confirmPassword" className="text-[var(--purple-ink)]">
                  Confirm Password <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="confirmPassword"
                  type="password"
                  value={formData.confirmPassword}
                  onChange={(e) => handleChange('confirmPassword', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="Re-enter password"
                />
                {formErrors.confirmPassword && (
                  <p className="text-sm text-red-500">{formErrors.confirmPassword}</p>
                )}
              </div>
            </div>

            {/* Name Fields */}
            <div className="grid md:grid-cols-2 gap-4">
              <div className="grid gap-2">
                <Label htmlFor="first_name" className="text-[var(--purple-ink)]">
                  First Name <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="first_name"
                  value={formData.first_name}
                  onChange={(e) => handleChange('first_name', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="Jane"
                />
                {formErrors.first_name && (
                  <p className="text-sm text-red-500">{formErrors.first_name}</p>
                )}
              </div>

              <div className="grid gap-2">
                <Label htmlFor="last_name" className="text-[var(--purple-ink)]">
                  Last Name <span className="text-red-500">*</span>
                </Label>
                <Input
                  id="last_name"
                  value={formData.last_name}
                  onChange={(e) => handleChange('last_name', e.target.value)}
                  className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  placeholder="Doe"
                />
                {formErrors.last_name && (
                  <p className="text-sm text-red-500">{formErrors.last_name}</p>
                )}
              </div>
            </div>

            {/* Phone */}
            <div className="grid gap-2">
              <Label htmlFor="phone" className="text-[var(--purple-ink)]">
                Phone <span className="text-red-500">*</span>
              </Label>
              <Input
                id="phone"
                type="tel"
                value={formData.phone}
                onChange={(e) => handleChange('phone', e.target.value)}
                className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                placeholder="(555) 123-4567"
              />
              {formErrors.phone && (
                <p className="text-sm text-red-500">{formErrors.phone}</p>
              )}
            </div>

            {/* Optional Fields Section */}
            {invitation?.role === 'member' && (
              <>
                <div className="border-t border-[var(--neutral-800)] pt-6 mt-2">
                  <h3 className="text-lg font-semibold text-[var(--purple-ink)] mb-4" style={{ fontFamily: "'Inter', sans-serif" }}>
                    Additional Information (Optional)
                  </h3>
                </div>

                {/* Address */}
                <div className="grid gap-2">
                  <Label htmlFor="address" className="text-[var(--purple-ink)]">Address</Label>
                  <Input
                    id="address"
                    value={formData.address}
                    onChange={(e) => handleChange('address', e.target.value)}
                    className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                    placeholder="123 Main St"
                  />
                </div>

                {/* City, State, Zipcode */}
                <div className="grid md:grid-cols-3 gap-4">
                  <div className="grid gap-2">
                    <Label htmlFor="city" className="text-[var(--purple-ink)]">City</Label>
                    <Input
                      id="city"
                      value={formData.city}
                      onChange={(e) => handleChange('city', e.target.value)}
                      className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                      placeholder="San Francisco"
                    />
                  </div>

                  <div className="grid gap-2">
                    <Label htmlFor="state" className="text-[var(--purple-ink)]">State</Label>
                    <Input
                      id="state"
                      value={formData.state}
                      onChange={(e) => handleChange('state', e.target.value)}
                      className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                      placeholder="CA"
                      maxLength={2}
                    />
                  </div>

                  <div className="grid gap-2">
                    <Label htmlFor="zipcode" className="text-[var(--purple-ink)]">Zipcode</Label>
                    <Input
                      id="zipcode"
                      value={formData.zipcode}
                      onChange={(e) => handleChange('zipcode', e.target.value)}
                      className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                      placeholder="94102"
                    />
                  </div>
                </div>

                {/* Date of Birth */}
                <div className="grid gap-2">
                  <Label htmlFor="date_of_birth" className="text-[var(--purple-ink)]">Date of Birth</Label>
                  <Input
                    id="date_of_birth"
                    type="date"
                    value={formData.date_of_birth}
                    onChange={(e) => handleChange('date_of_birth', e.target.value)}
                    className="rounded-xl border-2 border-[var(--neutral-800)] focus:border-brand-purple "
                  />
                </div>
              </>
            )}
          </div>

          {/* Submit Button */}
          <div className="mt-8">
            <Button
              type="submit"
              disabled={submitting}
              className="w-full h-14 rounded-xl bg-gradient-to-r from-[var(--green-light)] to-[var(--green-fern)] hover:from-[var(--green-fern)] hover:to-[var(--green-sage)] text-white text-lg font-semibold"
            >
              {submitting ? (
                <>
                  <Loader2 className="h-5 w-5 mr-2 animate-spin" />
                  Creating Your Account...
                </>
              ) : (
                <>
                  <CheckCircle className="h-5 w-5 mr-2" />
                  Accept Invitation & Create Account
                </>
              )}
            </Button>
          </div>
        </form>

        {/* Footer Note */}
        <div className="mt-6 text-center">
          <p className="text-sm text-brand-purple " style={{ fontFamily: "'Nunito Sans', sans-serif" }}>
            Already have an account?{' '}
            <button
              onClick={() => navigate('/login')}
              className="text-brand-purple  hover:text-[var(--purple-ink)] font-semibold underline"
            >
              Sign in instead
            </button>
          </p>
        </div>
      </Card>
    </div>
  );
};

export default AcceptInvitation;
