import { useState } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Repeat, Flower2 } from 'lucide-react'
import { getSubscriptions, createSubscription, setSubscriptionStatus, getStores, getProducts } from '../api/client'
import { money, useShop } from '../store/shop'
import StatusBadge from '../components/StatusBadge'
import { Link, useNavigate } from 'react-router-dom'

const FREQ = [['WEEKLY', 'Weekly'], ['BIWEEKLY', 'Every 2 Weeks'], ['MONTHLY', 'Monthly']]

export default function Subscription() {
  const qc = useQueryClient()
  const nav = useNavigate()
  const { custToken, storeId } = useShop()
  const [freq, setFreq] = useState('WEEKLY')
  const [productId, setProductId] = useState<number>(0)
  const [open, setOpen] = useState(false)

  const { data: subs } = useQuery({ queryKey: ['subs'], queryFn: getSubscriptions, enabled: !!custToken })
  const { data: stores } = useQuery({ queryKey: ['stores'], queryFn: () => getStores(true) })
  const { data: prods } = useQuery({ queryKey: ['sub-prods'], queryFn: () => getProducts({ size: 12, sort: 'sales' }) })
  const products = prods?.items || []

  const create = async () => {
    if (!custToken) { nav('/account'); return }
    const sid = storeId || stores?.[0]?.id
    const prod = products.find((p: any) => p.id === productId) || products[0]
    if (!prod) return
    await createSubscription({
      storeId: sid, productId: prod.id, sizeCode: 'ORIGINAL', frequency: freq,
      receiverName: '', receiverPhone: '', address: '', deliveryZip: '', price: prod.price,
    }).catch(() => {})
    setOpen(false); qc.invalidateQueries({ queryKey: ['subs'] })
  }
  const toggle = async (id: number, status: string) => {
    await setSubscriptionStatus(id, status === 'ACTIVE' ? 'PAUSED' : 'ACTIVE').catch(() => {})
    qc.invalidateQueries({ queryKey: ['subs'] })
  }
  const cancel = async (id: number) => { await setSubscriptionStatus(id, 'CANCELLED').catch(() => {}); qc.invalidateQueries({ queryKey: ['subs'] }) }

  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <div className="flex items-center gap-2 mb-2"><Repeat className="text-bloom" size={22} /><h1 className="font-serif text-2xl font-bold text-blush-900">Flower Subscription</h1></div>
      <p className="text-sm text-gray-500 mb-6">Get fresh flowers delivered weekly, every two weeks, or monthly.</p>

      {!custToken && <div className="bg-petal rounded-2xl p-6 text-center text-sm text-gray-600 mb-6">Please log in to start a subscription. <Link to="/account" className="text-bloom font-semibold">Log In →</Link></div>}

      <div className="bg-white rounded-2xl border border-blush-100/60 p-5 mb-6">
        {!open ? (
          <button onClick={() => custToken ? setOpen(true) : nav('/account')} className="bg-bloom text-white px-6 py-2.5 rounded-full font-semibold">Start a New Subscription</button>
        ) : (
          <div className="space-y-4">
            <div>
              <div className="text-sm font-medium mb-2">Delivery Frequency</div>
              <div className="flex gap-2">{FREQ.map(([v, l]) => <button key={v} onClick={() => setFreq(v)} className={`px-4 py-2 rounded-full text-sm border ${freq === v ? 'bg-bloom text-white border-bloom' : 'border-blush-100'}`}>{l}</button>)}</div>
            </div>
            <div>
              <div className="text-sm font-medium mb-2">Choose a Product</div>
              <select value={productId} onChange={e => setProductId(Number(e.target.value))} className="w-full px-3 py-2 rounded-xl border border-blush-100 text-sm bg-white">
                <option value={0}>Best Seller (Recommended)</option>
                {products.map((p: any) => <option key={p.id} value={p.id}>{p.name} — {money(p.price)}</option>)}
              </select>
            </div>
            <div className="flex gap-2">
              <button onClick={create} className="bg-bloom text-white px-6 py-2.5 rounded-full font-semibold">Start Subscription</button>
              <button onClick={() => setOpen(false)} className="border border-blush-100 px-6 py-2.5 rounded-full text-gray-600">Cancel</button>
            </div>
          </div>
        )}
      </div>

      <h2 className="font-serif text-lg font-bold mb-3">My Subscriptions</h2>
      <div className="space-y-3">
        {(subs || []).map((s: any) => (
          <div key={s.id} className="bg-white rounded-2xl border border-blush-100/60 p-4 flex items-center gap-4">
            <div className="w-14 h-14 bg-petal rounded-xl flex items-center justify-center"><Flower2 className="text-bloom/40" size={26} /></div>
            <div className="flex-1">
              <div className="font-medium text-sm">{s.productName || `상품 #${s.productId}`} · {FREQ.find(f => f[0] === s.frequency)?.[1] || s.frequency}</div>
              <div className="text-xs text-gray-500">다음 배송 {s.nextDeliveryDate || '-'} · {money(s.price)}</div>
            </div>
            <StatusBadge status={s.status} />
            {s.status !== 'CANCELLED' && (<>
              <button onClick={() => toggle(s.id, s.status)} className="text-xs text-bloom2 border border-blush-100 rounded-full px-3 py-1.5">{s.status === 'ACTIVE' ? '일시정지' : '재개'}</button>
              <button onClick={() => cancel(s.id)} className="text-xs text-blush-400 border border-blush-100 rounded-full px-3 py-1.5">해지</button>
            </>)}
          </div>
        ))}
        {!(subs || []).length && <div className="text-gray-400 text-sm py-8 text-center">아직 구독이 없습니다.</div>}
      </div>
    </div>
  )
}
