'use client'

import Link from 'next/link'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { apiFetch } from '@/lib/api'
import PublicShell from '@/components/layout/PublicShell'
import { marketplaceUrl } from '@/lib/urls'

type Step = 1 | 2 | 3

export default function OnboardingPage() {
  const router = useRouter()
  const [step, setStep] = useState<Step>(1)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const [company, setCompany] = useState({ name: '', slug: '' })
  const [brand, setBrand] = useState({
    displayName: '',
    tagline: '',
    primaryColor: '#2563eb',
    publicCity: '',
    publicCountry: '',
  })
  const [payments, setPayments] = useState({
    amanpayMerchantId: '',
    amanpaySecretKey: '',
    paypalEmail: '',
    isListedOnMarketplace: true,
  })

  async function handleStep1() {
    if (!company.name.trim()) return setError('Company name is required')
    setLoading(true)
    setError(null)
    try {
      await apiFetch('/companies/me', {
        method: 'PATCH',
        body: JSON.stringify({ name: company.name }),
      })
      setStep(2)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  async function handleStep2() {
    if (!brand.displayName.trim()) return setError('Display name is required')
    setLoading(true)
    setError(null)
    try {
      await apiFetch('/companies/me/brand', {
        method: 'PATCH',
        body: JSON.stringify({
          displayName: brand.displayName,
          tagline: brand.tagline || undefined,
          primaryColor: brand.primaryColor,
          publicCity: brand.publicCity || undefined,
          publicCountry: brand.publicCountry || undefined,
        }),
      })
      setStep(3)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  async function handleStep3() {
    setLoading(true)
    setError(null)
    try {
      await apiFetch('/companies/me/brand', {
        method: 'PATCH',
        body: JSON.stringify({
          amanpayMerchantId: payments.amanpayMerchantId || undefined,
          amanpaySecretKey: payments.amanpaySecretKey || undefined,
          paypalEmail: payments.paypalEmail || undefined,
          isListedOnMarketplace: payments.isListedOnMarketplace,
        }),
      })
      router.push('/dashboard')
    } catch (err: any) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }

  return (
    <PublicShell>
      <main className="flex items-center justify-center px-4 py-12">
        <div className="w-full max-w-lg">
        <div className="mb-8 text-center">
          <a href={marketplaceUrl} className="text-xs font-semibold uppercase tracking-widest text-blue-600">RentalDriveGo</a>
          <h1 className="mt-2 text-3xl font-bold text-slate-900">Set up your account</h1>
          <p className="mt-1 text-sm text-slate-500">Step {step} of 3</p>
        </div>

        <div className="flex gap-2 mb-8">
          {[1, 2, 3].map((s) => (
            <div
              key={s}
              className={`flex-1 h-1.5 rounded-full transition-colors ${
                s <= step ? 'bg-blue-600' : 'bg-slate-200'
              }`}
            />
          ))}
        </div>

        <div className="card p-8">
          {error && (
            <div className="mb-6 p-3 rounded-lg bg-red-50 border border-red-200 text-sm text-red-700">
              {error}
            </div>
          )}

          {step === 1 && (
            <div className="space-y-5">
              <div>
                <h2 className="text-lg font-semibold text-slate-900">Your company</h2>
                <p className="mt-1 text-sm text-slate-500">Tell us the basics about your rental company.</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Company name</label>
                <input
                  className="input-field"
                  placeholder="Casablanca Car Rentals"
                  value={company.name}
                  onChange={(e) => setCompany({ ...company, name: e.target.value })}
                />
              </div>
              <button onClick={handleStep1} disabled={loading} className="btn-primary w-full justify-center">
                {loading ? 'Saving…' : 'Continue'}
              </button>
            </div>
          )}

          {step === 2 && (
            <div className="space-y-5">
              <div>
                <h2 className="text-lg font-semibold text-slate-900">Brand &amp; identity</h2>
                <p className="mt-1 text-sm text-slate-500">Customize how your company appears to renters.</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Display name</label>
                <input
                  className="input-field"
                  placeholder="Casa Rentals"
                  value={brand.displayName}
                  onChange={(e) => setBrand({ ...brand, displayName: e.target.value })}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Tagline <span className="text-slate-400">(optional)</span></label>
                <input
                  className="input-field"
                  placeholder="The best fleet in the city"
                  value={brand.tagline}
                  onChange={(e) => setBrand({ ...brand, tagline: e.target.value })}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">City</label>
                  <input
                    className="input-field"
                    placeholder="Casablanca"
                    value={brand.publicCity}
                    onChange={(e) => setBrand({ ...brand, publicCity: e.target.value })}
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-slate-700 mb-1">Country</label>
                  <input
                    className="input-field"
                    placeholder="Morocco"
                    value={brand.publicCountry}
                    onChange={(e) => setBrand({ ...brand, publicCountry: e.target.value })}
                  />
                </div>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">Brand color</label>
                <div className="flex items-center gap-3">
                  <input
                    type="color"
                    className="h-10 w-14 rounded border border-slate-200 cursor-pointer"
                    value={brand.primaryColor}
                    onChange={(e) => setBrand({ ...brand, primaryColor: e.target.value })}
                  />
                  <input
                    className="input-field"
                    value={brand.primaryColor}
                    onChange={(e) => setBrand({ ...brand, primaryColor: e.target.value })}
                  />
                </div>
              </div>
              <div className="flex gap-3">
                <button onClick={() => setStep(1)} className="btn-secondary flex-1 justify-center">Back</button>
                <button onClick={handleStep2} disabled={loading} className="btn-primary flex-1 justify-center">
                  {loading ? 'Saving…' : 'Continue'}
                </button>
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="space-y-5">
              <div>
                <h2 className="text-lg font-semibold text-slate-900">Payment setup</h2>
                <p className="mt-1 text-sm text-slate-500">Connect payment providers so renters can book online. You can skip this for now.</p>
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">AmanPay Merchant ID <span className="text-slate-400">(optional)</span></label>
                <input
                  className="input-field"
                  placeholder="your-merchant-id"
                  value={payments.amanpayMerchantId}
                  onChange={(e) => setPayments({ ...payments, amanpayMerchantId: e.target.value })}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">AmanPay Secret Key <span className="text-slate-400">(optional)</span></label>
                <input
                  type="password"
                  className="input-field"
                  placeholder="your-secret-key"
                  value={payments.amanpaySecretKey}
                  onChange={(e) => setPayments({ ...payments, amanpaySecretKey: e.target.value })}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-slate-700 mb-1">PayPal email <span className="text-slate-400">(optional)</span></label>
                <input
                  type="email"
                  className="input-field"
                  placeholder="payments@yourcompany.com"
                  value={payments.paypalEmail}
                  onChange={(e) => setPayments({ ...payments, paypalEmail: e.target.value })}
                />
              </div>
              <label className="flex items-center gap-3 cursor-pointer">
                <input
                  type="checkbox"
                  className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
                  checked={payments.isListedOnMarketplace}
                  onChange={(e) => setPayments({ ...payments, isListedOnMarketplace: e.target.checked })}
                />
                <span className="text-sm text-slate-700">List my company on the RentalDriveGo marketplace</span>
              </label>
              <div className="flex gap-3">
                <button onClick={() => setStep(2)} className="btn-secondary flex-1 justify-center">Back</button>
                <button onClick={handleStep3} disabled={loading} className="btn-primary flex-1 justify-center">
                  {loading ? 'Finishing…' : 'Go to dashboard'}
                </button>
              </div>
            </div>
          )}
        </div>
        </div>
      </main>
    </PublicShell>
  )
}
