import { useState, useEffect } from 'react'
import { useNavigate, useSearchParams, Link } from 'react-router-dom'
import { useForm, Controller } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { clientsApi, lockersApi, rentalsApi } from '../../api'
import { ArrowLeftIcon, MagnifyingGlassIcon } from '@heroicons/react/24/outline'
import toast from 'react-hot-toast'
import { addDays, format } from 'date-fns'

const schema = z.object({
  client_id:         z.number({ required_error: 'Select a client' }).positive(),
  locker_id:         z.number({ required_error: 'Select a locker' }).positive(),
  start_date:        z.string().min(1, 'Start date required'),
  duration_days:     z.number().positive('Duration required'),
  rental_amount:     z.number().nonnegative(),
  deposit_amount:    z.number().nonnegative().default(0),
  deposit_collected: z.boolean().default(false),
  payment_method_id: z.number().positive('Payment method required'),
  notes:             z.string().optional(),
})
type FormData = z.infer<typeof schema>

export default function NewRentalPage() {
  const navigate = useNavigate()
  const qc = useQueryClient()
  const [params] = useSearchParams()
  const [clientSearch, setClientSearch] = useState('')
  const [lockerSearch, setLockerSearch] = useState('')
  const [selectedClient, setSelectedClient] = useState<any>(null)
  const [selectedLocker, setSelectedLocker] = useState<any>(null)

  const { register, handleSubmit, watch, setValue, control, formState: { errors } } = useForm<FormData>({
    resolver: zodResolver(schema),
    defaultValues: {
      start_date: format(new Date(), 'yyyy-MM-dd'),
      duration_days: 30,
      rental_amount: 0,
      deposit_amount: 0,
      deposit_collected: false,
    },
  })

  const startDate = watch('start_date')
  const durationDays = watch('duration_days')
  const endDate = startDate && durationDays ? format(addDays(new Date(startDate), durationDays), 'yyyy-MM-dd') : ''

  // Pre-select client from URL param
  const preClientId = params.get('client_id')
  const { data: preClient } = useQuery({
    queryKey: ['client', preClientId],
    queryFn: () => clientsApi.get(Number(preClientId)).then(r => r.data.data),
    enabled: Boolean(preClientId),
  })
  useEffect(() => {
    if (preClient) { setSelectedClient(preClient); setValue('client_id', preClient.id) }
  }, [preClient])

  // Client search
  const { data: clientResults } = useQuery({
    queryKey: ['clients-search', clientSearch],
    queryFn: () => clientsApi.list({ search: clientSearch, status: 'active', per_page: 8 }).then(r => r.data.data),
    enabled: clientSearch.length >= 2,
  })

  // Locker categories & available lockers
  const { data: categories } = useQuery({
    queryKey: ['locker-categories'],
    queryFn: () => lockersApi.categories().then(r => r.data),
  })
  const { data: availableLockers } = useQuery({
    queryKey: ['lockers-available', lockerSearch],
    queryFn: () => lockersApi.available({ search: lockerSearch }).then(r => r.data.data),
  })

  // When locker selected, set deposit from locker
  useEffect(() => {
    if (selectedLocker) {
      setValue('locker_id', selectedLocker.id)
      setValue('deposit_amount', Number(selectedLocker.deposit_amount ?? 0))
      // Set price from category base_price
      const cat = categories?.find((c: any) => c.id === selectedLocker.category_id)
      if (cat) setValue('rental_amount', Number(cat.base_price))
    }
  }, [selectedLocker, categories])

  // Payment methods from categories query response or hardcoded
  const paymentMethods = [
    { id: 1, name: 'Cash' }, { id: 2, name: 'bKash' },
    { id: 3, name: 'Nagad' }, { id: 4, name: 'SSLCommerz' },
  ]

  const mutation = useMutation({
    mutationFn: (data: FormData) => rentalsApi.create(data),
    onSuccess: (res) => {
      qc.invalidateQueries({ queryKey: ['rentals'] })
      qc.invalidateQueries({ queryKey: ['lockers'] })
      toast.success('Rental created successfully!')
      navigate(`/rentals/${res.data.data.id}`)
    },
    onError: (err: any) => {
      const msg = err.response?.data?.message
      toast.error(msg || 'Failed to create rental.')
    },
  })

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <div className="flex items-center gap-3">
        <Link to="/rentals" className="p-2 text-slate-400 hover:text-white hover:bg-slate-700 rounded-lg transition-colors">
          <ArrowLeftIcon className="w-5 h-5" />
        </Link>
        <div>
          <h1 className="text-2xl font-bold text-white">New Rental</h1>
          <p className="text-slate-400 text-sm">Assign a locker to a client</p>
        </div>
      </div>

      <form onSubmit={handleSubmit((d) => mutation.mutate(d))} className="space-y-5">

        {/* Step 1 — Client */}
        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">
            <span className="bg-blue-600 text-white text-xs font-bold rounded-full w-5 h-5 inline-flex items-center justify-center mr-2">1</span>
            Select Client
          </h2>

          {selectedClient ? (
            <div className="flex items-center justify-between p-3 bg-slate-700 rounded-lg">
              <div className="flex items-center gap-3">
                <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-sm font-bold text-white">
                  {selectedClient.full_name.charAt(0)}
                </div>
                <div>
                  <p className="font-medium text-white">{selectedClient.full_name}</p>
                  <p className="text-xs text-slate-400">{selectedClient.phone}</p>
                </div>
              </div>
              <button type="button" onClick={() => { setSelectedClient(null); setValue('client_id', 0 as any) }}
                className="text-slate-400 hover:text-red-400 text-sm">Change</button>
            </div>
          ) : (
            <div>
              <div className="relative">
                <MagnifyingGlassIcon className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input
                  value={clientSearch}
                  onChange={(e) => setClientSearch(e.target.value)}
                  className="input pl-9"
                  placeholder="Search client by name or phone…"
                />
              </div>
              {clientResults && clientResults.length > 0 && (
                <div className="mt-2 bg-slate-700 rounded-lg overflow-hidden border border-slate-600">
                  {clientResults.map((c: any) => (
                    <button
                      key={c.id} type="button"
                      onClick={() => { setSelectedClient(c); setValue('client_id', c.id); setClientSearch('') }}
                      className="w-full flex items-center gap-3 p-3 hover:bg-slate-600 transition-colors text-left"
                    >
                      <div className="w-7 h-7 bg-slate-500 rounded-full flex items-center justify-center text-xs font-bold text-white">
                        {c.full_name.charAt(0)}
                      </div>
                      <div>
                        <p className="text-sm font-medium text-white">{c.full_name}</p>
                        <p className="text-xs text-slate-400">{c.phone}</p>
                      </div>
                    </button>
                  ))}
                </div>
              )}
              {errors.client_id && <p className="text-red-400 text-xs mt-1">Please select a client</p>}
            </div>
          )}
        </div>

        {/* Step 2 — Locker */}
        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">
            <span className="bg-blue-600 text-white text-xs font-bold rounded-full w-5 h-5 inline-flex items-center justify-center mr-2">2</span>
            Select Available Locker
          </h2>

          {selectedLocker ? (
            <div className="flex items-center justify-between p-3 bg-slate-700 rounded-lg">
              <div>
                <p className="font-mono font-bold text-white">{selectedLocker.locker_number}</p>
                <p className="text-xs text-slate-400">{selectedLocker.category?.name} · {selectedLocker.zone?.name ?? 'No zone'}</p>
              </div>
              <button type="button" onClick={() => { setSelectedLocker(null); setValue('locker_id', 0 as any) }}
                className="text-slate-400 hover:text-red-400 text-sm">Change</button>
            </div>
          ) : (
            <div>
              <div className="relative mb-3">
                <MagnifyingGlassIcon className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
                <input value={lockerSearch} onChange={(e) => setLockerSearch(e.target.value)}
                  className="input pl-9" placeholder="Filter by locker number…" />
              </div>
              <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2 max-h-52 overflow-y-auto">
                {(availableLockers ?? []).map((l: any) => (
                  <button
                    key={l.id} type="button"
                    onClick={() => setSelectedLocker(l)}
                    className="border border-green-700 bg-green-900/30 text-green-300 rounded-lg p-2 text-center hover:bg-green-900/60 transition-colors"
                  >
                    <p className="font-mono font-bold text-sm">{l.locker_number}</p>
                    <p className="text-xs opacity-70">{l.category?.name}</p>
                  </button>
                ))}
                {availableLockers?.length === 0 && (
                  <p className="col-span-5 text-slate-400 text-sm text-center py-4">No available lockers.</p>
                )}
              </div>
              {errors.locker_id && <p className="text-red-400 text-xs mt-1">Please select a locker</p>}
            </div>
          )}
        </div>

        {/* Step 3 — Duration & Amount */}
        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">
            <span className="bg-blue-600 text-white text-xs font-bold rounded-full w-5 h-5 inline-flex items-center justify-center mr-2">3</span>
            Duration & Pricing
          </h2>

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">Start Date</label>
              <input {...register('start_date')} type="date" className="input" />
              {errors.start_date && <p className="text-red-400 text-xs mt-1">{errors.start_date.message}</p>}
            </div>
            <div>
              <label className="label">Duration (days)</label>
              <input {...register('duration_days', { valueAsNumber: true })} type="number" min="1" className="input" />
            </div>
          </div>

          {/* Quick duration presets */}
          {selectedLocker && categories && (
            <div>
              <label className="label">Quick Select Duration</label>
              <div className="flex flex-wrap gap-2">
                {(categories.find((c: any) => c.id === selectedLocker.category_id)?.pricing ?? []).map((p: any) => (
                  <button
                    key={p.id} type="button"
                    onClick={() => { setValue('duration_days', p.duration_days); setValue('rental_amount', Number(p.price)) }}
                    className="px-3 py-1.5 rounded-lg border border-slate-600 text-sm hover:border-blue-500 hover:bg-blue-900/20 transition-colors text-slate-300"
                  >
                    {p.duration_label} — ৳{Number(p.price).toLocaleString()}
                  </button>
                ))}
              </div>
            </div>
          )}

          {endDate && (
            <div className="bg-slate-700/50 rounded-lg p-3 text-sm text-slate-300">
              Rental period: <strong className="text-white">{startDate}</strong> → <strong className="text-white">{endDate}</strong>
            </div>
          )}

          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="label">Rental Amount (৳)</label>
              <input {...register('rental_amount', { valueAsNumber: true })} type="number" min="0" step="0.01" className="input" />
            </div>
            <div>
              <label className="label">Key Deposit (৳)</label>
              <input {...register('deposit_amount', { valueAsNumber: true })} type="number" min="0" step="0.01" className="input" />
            </div>
          </div>

          <div className="flex items-center gap-2">
            <input {...register('deposit_collected')} type="checkbox" id="dep_collected" className="w-4 h-4 accent-blue-600" />
            <label htmlFor="dep_collected" className="text-sm text-slate-300">Deposit collected at time of assignment</label>
          </div>
        </div>

        {/* Step 4 — Payment */}
        <div className="card space-y-4">
          <h2 className="font-semibold text-white border-b border-slate-700 pb-3">
            <span className="bg-blue-600 text-white text-xs font-bold rounded-full w-5 h-5 inline-flex items-center justify-center mr-2">4</span>
            Payment Method
          </h2>
          <div>
            <label className="label">Payment Method <span className="text-red-400">*</span></label>
            <select {...register('payment_method_id', { valueAsNumber: true })} className="input">
              <option value="">Select payment method</option>
              {paymentMethods.map(m => (
                <option key={m.id} value={m.id}>{m.name}</option>
              ))}
            </select>
            {errors.payment_method_id && <p className="text-red-400 text-xs mt-1">{errors.payment_method_id.message}</p>}
          </div>
          <div>
            <label className="label">Notes</label>
            <textarea {...register('notes')} className="input h-20 resize-none" placeholder="Optional notes…" />
          </div>
        </div>

        {/* Summary */}
        <div className="card bg-slate-700/50">
          <h2 className="font-semibold text-white mb-3">Summary</h2>
          <div className="space-y-1 text-sm">
            <div className="flex justify-between">
              <span className="text-slate-400">Client</span>
              <span className="text-white">{selectedClient?.full_name ?? '—'}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-400">Locker</span>
              <span className="font-mono text-white">{selectedLocker?.locker_number ?? '—'}</span>
            </div>
            <div className="flex justify-between">
              <span className="text-slate-400">Period</span>
              <span className="text-white">{startDate} → {endDate || '—'}</span>
            </div>
            <div className="flex justify-between border-t border-slate-600 pt-2 mt-2 font-semibold">
              <span className="text-slate-300">Total Payable</span>
              <span className="text-white">৳{((watch('rental_amount') || 0) + (watch('deposit_collected') ? (watch('deposit_amount') || 0) : 0)).toLocaleString()}</span>
            </div>
          </div>
        </div>

        <div className="flex gap-3 justify-end">
          <Link to="/rentals" className="btn-secondary">Cancel</Link>
          <button type="submit" disabled={mutation.isPending} className="btn-primary px-8">
            {mutation.isPending ? 'Creating…' : 'Create Rental'}
          </button>
        </div>
      </form>
    </div>
  )
}
