'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 { carplaceUrl } 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 [showSecretKey, setShowSecretKey] = useState(false)

  const [company, setCompany] = useState({ name: '', slug: '' })
  const [brand, setBrand] = useState({
    displayName: '',
    tagline: '',
    primaryColor: '#2563eb',
    publicCity: '',
    publicCountry: '',
  })
  const [payments, setPayments] = useState({
    amanpayMerchantId: '',
    amanpaySecretKey: '',
    paypalEmail: '',
    isListedOnCarplace: 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,
          isListedOnCarplace: payments.isListedOnCarplace,
        }),
      })
      router.push('/')
    } 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={carplaceUrl} 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>
                <div className="relative">
                  <input
                    type={showSecretKey ? 'text' : 'password'}
                    className="input-field pr-10"
                    placeholder="your-secret-key"
                    value={payments.amanpaySecretKey}
                    onChange={(e) => setPayments({ ...payments, amanpaySecretKey: e.target.value })}
                  />
                  <button
                    type="button"
                    onClick={() => setShowSecretKey((v) => !v)}
                    className="absolute inset-y-0 right-3 flex items-center text-slate-400 hover:text-slate-600"
                    tabIndex={-1}
                  >
                    {showSecretKey ? (
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />
                      </svg>
                    ) : (
                      <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                        <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                      </svg>
                    )}
                  </button>
                </div>
              </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.isListedOnCarplace}
                  onChange={(e) => setPayments({ ...payments, isListedOnCarplace: e.target.checked })}
                />
                <span className="text-sm text-slate-700">List my company on the RentalDriveGo Carplace</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>
  )
}
