import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft, Phone, Shield, Check } from 'lucide-react';
import { useChatStore } from '@/features/chat/presentation/stores/chatStore';

export default function BindPhonePage() {
  const navigate = useNavigate();
  const { userId } = useChatStore();
  const [phone, setPhone] = useState('');
  const [code, setCode] = useState('');
  const [codeSent, setCodeSent] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);

  const sendCode = async () => {
    if (!phone || phone.length < 11) {
      setError('请输入正确的手机号');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/v1/users/send-code', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-user-id': userId!,
        },
        body: JSON.stringify({ phone }),
      });
      const data = await response.json();

      if (data.success) {
        setCodeSent(true);
        // 开始倒计时
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        setError(data.message || '发送失败，请稍后重试');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const bindPhone = async () => {
    if (!code || code.length < 4) {
      setError('请输入验证码');
      return;
    }

    setLoading(true);
    setError('');

    try {
      const response = await fetch('/api/v1/users/bind-phone', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'x-user-id': userId!,
        },
        body: JSON.stringify({ phone, code }),
      });
      const data = await response.json();

      if (data.success) {
        setSuccess(true);
        // 保存手机号到本地存储
        localStorage.setItem('userPhone', phone);
        // 2秒后跳转
        setTimeout(() => {
          navigate('/profile');
        }, 2000);
      } else {
        setError(data.message || '绑定失败，请检查验证码');
      }
    } catch (err) {
      setError('网络错误，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  if (success) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-blue-50 to-white flex items-center justify-center">
        <div className="text-center">
          <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <Check className="w-8 h-8 text-green-600" />
          </div>
          <h2 className="text-xl font-semibold text-secondary-900 mb-2">绑定成功</h2>
          <p className="text-secondary-500">正在跳转...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-white">
      {/* Header */}
      <header className="sticky top-0 z-10 bg-white/80 backdrop-blur-md border-b border-secondary-200">
        <div className="max-w-2xl mx-auto px-4 py-4 flex items-center gap-4">
          <button
            onClick={() => navigate(-1)}
            className="p-2 hover:bg-secondary-100 rounded-lg transition-colors"
          >
            <ArrowLeft className="w-5 h-5 text-secondary-600" />
          </button>
          <h1 className="text-lg font-semibold text-secondary-900">绑定手机</h1>
        </div>
      </header>

      {/* Content */}
      <main className="max-w-md mx-auto px-4 py-8">
        <div className="bg-white rounded-2xl shadow-sm border border-secondary-200 p-6">
          {/* Icon */}
          <div className="w-16 h-16 bg-primary-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <Phone className="w-8 h-8 text-primary-600" />
          </div>

          <h2 className="text-xl font-semibold text-secondary-900 text-center mb-2">
            绑定手机号
          </h2>
          <p className="text-sm text-secondary-500 text-center mb-6">
            绑定手机号后可保存对话记录，跨设备同步数据
          </p>

          {/* Error */}
          {error && (
            <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm">
              {error}
            </div>
          )}

          {/* Phone Input */}
          <div className="mb-4">
            <label className="block text-sm font-medium text-secondary-700 mb-1.5">
              手机号
            </label>
            <div className="flex gap-2">
              <div className="relative flex-1">
                <Phone className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-secondary-400" />
                <input
                  type="tel"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value.replace(/\D/g, '').slice(0, 11))}
                  placeholder="请输入手机号"
                  className="w-full pl-10 pr-4 py-2.5 border border-secondary-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500/20 focus:border-primary-500"
                  disabled={codeSent && countdown > 0}
                />
              </div>
              <button
                onClick={sendCode}
                disabled={loading || countdown > 0 || phone.length < 11}
                className="px-4 py-2.5 bg-primary-100 text-primary-700 rounded-lg hover:bg-primary-200 disabled:opacity-50 disabled:cursor-not-allowed whitespace-nowrap"
              >
                {countdown > 0 ? `${countdown}s` : '获取验证码'}
              </button>
            </div>
          </div>

          {/* Code Input */}
          {codeSent && (
            <div className="mb-6">
              <label className="block text-sm font-medium text-secondary-700 mb-1.5">
                验证码
              </label>
              <div className="relative">
                <Shield className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-secondary-400" />
                <input
                  type="text"
                  value={code}
                  onChange={(e) => setCode(e.target.value.replace(/\D/g, '').slice(0, 6))}
                  placeholder="请输入验证码"
                  className="w-full pl-10 pr-4 py-2.5 border border-secondary-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500/20 focus:border-primary-500"
                />
              </div>
            </div>
          )}

          {/* Submit Button */}
          <button
            onClick={bindPhone}
            disabled={loading || !codeSent || code.length < 4}
            className="w-full py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed font-medium"
          >
            {loading ? '处理中...' : '确认绑定'}
          </button>
        </div>

        {/* Back */}
        <button
          onClick={() => navigate('/chat')}
          className="w-full mt-4 py-3 text-secondary-500 hover:text-secondary-700 transition-colors"
        >
          暂不绑定，返回对话
        </button>
      </main>
    </div>
  );
}
