import { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { api } from '../../api/client';
import { formatPrice } from '../../utils/date';

export default function RegisterPage() {
  const navigate = useNavigate();
  const [plans, setPlans] = useState([]);
  const [form, setForm] = useState({
    fullName: '',
    phone: '',
    email: '',
    password: '',
    confirmPassword: '',
    affiliateCode: '',
    planMonths: 12,
  });
  const [receipt, setReceipt] = useState(null);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    api.get('/payments/plans').then(({ data }) => setPlans(data.plans)).catch(() => {});
  }, []);

  const selectedPlan = plans.find((p) => p.months === form.planMonths) || plans[3];

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (form.password !== form.confirmPassword) {
      setError('رمز عبور و تکرار آن یکسان نیست');
      return;
    }
    setError('');
    setLoading(true);
    try {
      await api.post('/auth/register', {
        fullName: form.fullName,
        phone: form.phone,
        email: form.email,
        password: form.password,
        planMonths: form.planMonths,
        affiliateCode: form.affiliateCode || undefined,
      });
      navigate('/login', { state: { message: 'ثبت‌نام موفق. وارد شوید.' } });
    } catch (err) {
      setError(err.response?.data?.error || 'خطا در ثبت‌نام');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-navy-950 py-12 px-4">
      <div className="max-w-lg mx-auto">
        <Link to="/login" className="text-accent text-sm mb-6 inline-block">← بازگشت به ورود</Link>
        <h1 className="text-2xl font-bold mb-2">ثبت‌نام مشتری</h1>
        <p className="text-gray-500 text-sm mb-8">پس از ثبت‌نام، فیش پرداخت را آپلود کنید</p>

        <form onSubmit={handleSubmit} className="card space-y-4">
          {error && <div className="p-3 rounded-xl bg-red-500/20 text-red-400 text-sm">{error}</div>}
          {['fullName', 'phone', 'email'].map((field) => (
            <div key={field}>
              <label className="text-sm text-gray-400 mb-1 block">
                {field === 'fullName' ? 'نام کامل' : field === 'phone' ? 'شماره موبایل' : 'ایمیل'}
              </label>
              <input
                className="input-field"
                type={field === 'email' ? 'email' : 'text'}
                value={form[field]}
                onChange={(e) => setForm({ ...form, [field]: e.target.value })}
                required={field !== 'phone'}
                dir={field === 'email' ? 'ltr' : 'rtl'}
              />
            </div>
          ))}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-sm text-gray-400 mb-1 block">رمز عبور</label>
              <input type="password" className="input-field" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} required dir="ltr" />
            </div>
            <div>
              <label className="text-sm text-gray-400 mb-1 block">تکرار رمز</label>
              <input type="password" className="input-field" value={form.confirmPassword} onChange={(e) => setForm({ ...form, confirmPassword: e.target.value })} required dir="ltr" />
            </div>
          </div>
          <div>
            <label className="text-sm text-gray-400 mb-1 block">کد معرف (اختیاری)</label>
            <input className="input-field" value={form.affiliateCode} onChange={(e) => setForm({ ...form, affiliateCode: e.target.value })} />
          </div>

          <div>
            <label className="text-sm text-gray-400 mb-2 block">انتخاب پکیج</label>
            <div className="grid grid-cols-4 gap-2">
              {[1, 3, 6, 12].map((m) => (
                <button
                  key={m}
                  type="button"
                  onClick={() => setForm({ ...form, planMonths: m })}
                  className={`py-3 rounded-xl border text-sm font-medium transition-colors ${
                    form.planMonths === m ? 'border-accent bg-accent/20 text-accent' : 'border-navy-700 text-gray-400'
                  }`}
                >
                  {m} ماه
                </button>
              ))}
            </div>
          </div>

          {selectedPlan && (
            <div className="bg-navy-900 rounded-xl p-4 text-sm space-y-1">
              <div className="flex justify-between">
                <span className="text-gray-500">قیمت اصلی</span>
                <span>{formatPrice(selectedPlan.originalPrice)} تومان</span>
              </div>
              {selectedPlan.discountPercent > 0 && (
                <div className="flex justify-between text-emerald-400">
                  <span>تخفیف ({selectedPlan.discountPercent}%)</span>
                  <span>−{formatPrice(Math.round((selectedPlan.originalPrice * selectedPlan.discountPercent) / 100))}</span>
                </div>
              )}
              <div className="flex justify-between font-bold pt-2 border-t border-navy-700">
                <span>مبلغ نهایی</span>
                <span className="text-accent">{formatPrice(selectedPlan.finalPrice)} تومان</span>
              </div>
            </div>
          )}

          <div
            className="border-2 border-dashed border-navy-700 rounded-xl p-8 text-center cursor-pointer hover:border-accent"
            onClick={() => document.getElementById('receipt').click()}
          >
            <input id="receipt" type="file" className="hidden" accept=".jpg,.jpeg,.png,.pdf" onChange={(e) => setReceipt(e.target.files[0])} />
            <p className="text-gray-400 text-sm">آپلود فیش بانکی (JPG, PNG, PDF — حداکثر ۵MB)</p>
            {receipt && <p className="text-accent text-sm mt-2">{receipt.name}</p>}
          </div>

          <button type="submit" className="btn-primary" disabled={loading}>
            {loading ? 'در حال ثبت...' : 'ثبت‌نام و ارسال فیش'}
          </button>
        </form>

        <p className="text-center mt-6 text-sm">
          <Link to="/cooperation" className="text-accent hover:underline">
            درخواست همکاری
          </Link>
        </p>
      </div>
    </div>
  );
}
