import { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';

function LockIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
      <path strokeLinecap="round" strokeLinejoin="round" d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z" />
    </svg>
  );
}

function SmsIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
      <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 1.5H8.25A2.25 2.25 0 0 0 6 3.75v16.5a2.25 2.25 0 0 0 2.25 2.25h7.5A2.25 2.25 0 0 0 18 20.25V3.75a2.25 2.25 0 0 0-2.25-2.25H13.5m-3 0V3h3V1.5m-3 0h3m-3 18.75h3" />
    </svg>
  );
}

function EmailLoginTab({ onSuccess }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const { login, loading, error, clearError } = useAuthStore();

  const handleSubmit = async (e) => {
    e.preventDefault();
    clearError();
    const success = await login(email, password);
    if (success) onSuccess();
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {error && (
        <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {error}
        </div>
      )}
      <div>
        <label className="mb-2 block text-sm font-semibold text-slate-700">Email</label>
        <input
          type="email"
          value={email}
          onChange={(e) => { clearError(); setEmail(e.target.value); }}
          className="w-full rounded-2xl border border-slate-200 bg-white/80 px-4 py-3 text-sm text-slate-900 placeholder-slate-400 shadow-sm transition focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
          placeholder="your@email.com"
          required
        />
      </div>
      <div>
        <label className="mb-2 block text-sm font-semibold text-slate-700">Password</label>
        <input
          type="password"
          value={password}
          onChange={(e) => { clearError(); setPassword(e.target.value); }}
          className="w-full rounded-2xl border border-slate-200 bg-white/80 px-4 py-3 text-sm text-slate-900 placeholder-slate-400 shadow-sm transition focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
          placeholder="Your password"
          required
        />
      </div>
      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-2xl bg-[linear-gradient(135deg,#0891b2,#0f172a)] py-3 text-sm font-semibold text-white shadow-[0_12px_25px_rgba(8,145,178,0.35)] transition-transform hover:-translate-y-0.5 disabled:opacity-60 disabled:hover:translate-y-0"
      >
        {loading ? 'Logging in...' : 'Login'}
      </button>
    </form>
  );
}

function SmsLoginTab({ onSuccess }) {
  const [step, setStep] = useState(1);
  const [rollNo, setRollNo] = useState('');
  const [phone, setPhone] = useState('');
  const [otp, setOtp] = useState('');
  const { requestSmsToken, loginWithSmsToken, loading, error, clearError } = useAuthStore();

  const handleRequestToken = async (e) => {
    e.preventDefault();
    clearError();
    const success = await requestSmsToken(rollNo, phone);
    if (success) setStep(2);
  };

  const handleVerifyToken = async (e) => {
    e.preventDefault();
    clearError();
    const success = await loginWithSmsToken(rollNo, otp);
    if (success) onSuccess();
  };

  const handleBack = () => {
    clearError();
    setStep(1);
    setOtp('');
  };

  if (step === 2) {
    return (
      <form onSubmit={handleVerifyToken} className="space-y-4">
        <div className="rounded-2xl border border-cyan-200 bg-cyan-50 px-4 py-3 text-sm text-cyan-800">
          A 6-digit token has been sent to your phone number. It expires in 10 minutes.
        </div>

        {error && (
          <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
            {error}
          </div>
        )}

        <div>
          <label className="mb-2 block text-sm font-semibold text-slate-700">SMS Token (6 digits)</label>
          <input
            type="text"
            value={otp}
            onChange={(e) => { clearError(); setOtp(e.target.value.replace(/\D/g, '').slice(0, 6)); }}
            className="w-full rounded-2xl border border-slate-200 bg-white/80 px-4 py-3 text-center text-2xl font-bold tracking-[0.5em] text-slate-900 shadow-sm transition focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
            placeholder="000000"
            maxLength={6}
            required
          />
        </div>

        <button
          type="submit"
          disabled={loading || otp.length !== 6}
          className="w-full rounded-2xl bg-[linear-gradient(135deg,#0891b2,#0f172a)] py-3 text-sm font-semibold text-white shadow-[0_12px_25px_rgba(8,145,178,0.35)] transition-transform hover:-translate-y-0.5 disabled:opacity-60 disabled:hover:translate-y-0"
        >
          {loading ? 'Verifying...' : 'Verify Token'}
        </button>

        <button
          type="button"
          onClick={handleBack}
          className="w-full rounded-2xl border border-slate-200 bg-white py-3 text-sm font-medium text-slate-600 transition hover:bg-slate-50"
        >
          Back
        </button>
      </form>
    );
  }

  return (
    <form onSubmit={handleRequestToken} className="space-y-4">
      {error && (
        <div className="rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {error}
        </div>
      )}
      <div>
        <label className="mb-2 block text-sm font-semibold text-slate-700">Roll Number</label>
        <input
          type="text"
          value={rollNo}
          onChange={(e) => { clearError(); setRollNo(e.target.value); }}
          className="w-full rounded-2xl border border-slate-200 bg-white/80 px-4 py-3 text-sm text-slate-900 placeholder-slate-400 shadow-sm transition focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
          placeholder="Roll number"
          required
        />
      </div>
      <div>
        <label className="mb-2 block text-sm font-semibold text-slate-700">Phone Number</label>
        <input
          type="tel"
          value={phone}
          onChange={(e) => { clearError(); setPhone(e.target.value); }}
          className="w-full rounded-2xl border border-slate-200 bg-white/80 px-4 py-3 text-sm text-slate-900 placeholder-slate-400 shadow-sm transition focus:border-cyan-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/20"
          placeholder="0712 345 678"
          required
        />
      </div>
      <button
        type="submit"
        disabled={loading}
        className="w-full rounded-2xl bg-[linear-gradient(135deg,#0891b2,#0f172a)] py-3 text-sm font-semibold text-white shadow-[0_12px_25px_rgba(8,145,178,0.35)] transition-transform hover:-translate-y-0.5 disabled:opacity-60 disabled:hover:translate-y-0"
      >
        {loading ? 'Sending token...' : 'Send SMS Token'}
      </button>
    </form>
  );
}

export default function Login() {
  const [tab, setTab] = useState('email');
  const navigate = useNavigate();
  const { clearError } = useAuthStore();

  const handleSuccess = () => navigate('/', { replace: true });

  const switchTab = (t) => {
    clearError();
    setTab(t);
  };

  return (
    <div className="min-h-screen bg-[linear-gradient(180deg,rgba(14,116,144,0.96),rgba(15,23,42,0.98))] flex items-center justify-center px-4">

      <div className="pointer-events-none fixed inset-0 overflow-hidden">
        <div className="absolute left-[-8rem] top-[-8rem] h-[20rem] w-[20rem] rounded-full bg-cyan-400/15 blur-3xl" />
        <div className="absolute right-[-8rem] bottom-[-8rem] h-[20rem] w-[20rem] rounded-full bg-sky-500/10 blur-3xl" />
      </div>

      <div className="relative w-full max-w-md">

        <div className="mb-6 text-center">
          <div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-3xl bg-[linear-gradient(135deg,rgba(255,255,255,0.25),rgba(255,255,255,0.08))] border border-white/20 shadow-[0_16px_40px_rgba(0,0,0,0.3)] backdrop-blur">
            <span className="text-2xl font-bold text-white">A</span>
          </div>
          <h1 className="text-2xl font-bold text-white">AWTF Portal</h1>
          <p className="mt-1 text-sm text-cyan-100/70">Advocates Welfare Trust Fund</p>
        </div>

        <div className="overflow-hidden rounded-[32px] border border-white/12 bg-white shadow-[0_40px_80px_rgba(0,0,0,0.4)]">

          <div className="flex border-b border-slate-100">
            <button
              onClick={() => switchTab('email')}
              className={`flex flex-1 items-center justify-center gap-2 py-4 text-sm font-semibold transition-colors ${
                tab === 'email'
                  ? 'border-b-2 border-cyan-600 text-cyan-700 bg-cyan-50/60'
                  : 'text-slate-500 hover:text-slate-700'
              }`}
            >
              <LockIcon />
              Email
            </button>
            <button
              onClick={() => switchTab('sms')}
              className={`flex flex-1 items-center justify-center gap-2 py-4 text-sm font-semibold transition-colors ${
                tab === 'sms'
                  ? 'border-b-2 border-cyan-600 text-cyan-700 bg-cyan-50/60'
                  : 'text-slate-500 hover:text-slate-700'
              }`}
            >
              <SmsIcon />
              SMS Token
            </button>
          </div>

          <div className="p-6">
            {tab === 'email' ? (
              <>
                <p className="mb-5 text-sm text-slate-500">Sign in with your email and password.</p>
                <EmailLoginTab onSuccess={handleSuccess} />
                <p className="mt-5 text-center text-sm text-slate-500">
                  Have an invitation link?{' '}
                  <Link to="/register" className="font-semibold text-cyan-700 hover:underline">
                    Join here
                  </Link>
                </p>
              </>
            ) : (
              <>
                <p className="mb-5 text-sm text-slate-500">
                  Enter your roll number and registered phone number to receive a one-time token via SMS.
                </p>
                <SmsLoginTab onSuccess={handleSuccess} />
              </>
            )}
          </div>
        </div>

        <p className="mt-6 text-center text-xs text-cyan-100/50">
          &copy; {new Date().getFullYear()} Advocates Welfare Trust Fund
        </p>
      </div>
    </div>
  );
}
