import { createFileRoute } from '@tanstack/react-router'
import { trpc } from '../lib/trpc-client'
import { useState } from 'react'
import { p, MyButton, AppContainer, div } from 'web-components'
import { Ticket, AlertCircle } from 'lucide-react'
import dayjs from 'dayjs'

export const Route = createFileRoute('/me/coupons')({ component: CouponsPage })

interface Coupon {
  id: number
  code: string
  discountType: 'percentage' | 'flat'
  discountValue: number
  maxValue?: number
  minOrder?: number
  description: string
  validTill?: string | Date
  usageCount: number
  maxLimitForUser?: number
  isExpired: boolean
  isUsedUp: boolean
}

interface CouponCardProps {
  coupon: Coupon
}

function CouponCard({ coupon }: CouponCardProps) {
  const getStatusColor = () => {
    if (coupon.isExpired) return 'text-red-500'
    if (coupon.isUsedUp) return 'text-orange-500'
    return 'text-green-600'
  }

  const getStatusText = () => {
    if (coupon.isExpired) return 'Expired'
    if (coupon.isUsedUp) return 'Used'
    return 'Available'
  }

  const formatDate = (date?: string | Date) => {
    if (!date) return 'No expiry'
    return dayjs(date).format('DD MMM YYYY')
  }

  return (
    <div className="mb-3 rounded-lg border border-gray-100 bg-white p-4 shadow-sm">
      <div className="mb-2 flex items-start justify-between">
        <div className="flex-1">
          <p className="mb-1 text-lg font-semibold text-gray-800">{coupon.code}</p>
          <p className="mb-2 text-sm text-gray-600">{coupon.description}</p>
        </div>
        <div className="items-end text-right">
          <p className={`mb-1 text-sm font-medium ${getStatusColor()}`}>{getStatusText()}</p>
          {coupon.maxLimitForUser && (
            <p className="text-xs text-gray-500">Used: {coupon.usageCount}/{coupon.maxLimitForUser}</p>
          )}
        </div>
      </div>

      <div className="flex items-center justify-between">
        <p className="text-xs text-gray-500">Valid till: {formatDate(coupon.validTill)}</p>
        <button
          className={`rounded-full px-3 py-1 text-xs font-medium text-white ${
            coupon.isExpired || coupon.isUsedUp
              ? 'cursor-not-allowed bg-gray-400'
              : 'bg-blue-500 hover:bg-blue-600'
          }`}
          disabled={coupon.isExpired || coupon.isUsedUp}
        >
          {coupon.isExpired || coupon.isUsedUp ? 'Unavailable' : 'Apply'}
        </button>
      </div>
    </div>
  )
}

interface CouponSectionProps {
  title: string
  coupons: Coupon[]
  emptyMessage: string
}

function CouponSection({ title, coupons, emptyMessage }: CouponSectionProps) {
  return (
    <div className="mb-6">
      <p className="mb-3 text-lg font-semibold text-gray-800">{title}</p>

      {coupons.length === 0 ? (
        <div className="flex flex-col items-center rounded-lg bg-gray-50 p-6">
          <Ticket className="mb-2 h-12 w-12 text-gray-400" />
          <p className="text-center text-gray-500">{emptyMessage}</p>
        </div>
      ) : (
        coupons.map((coupon) => <CouponCard key={coupon.id} coupon={coupon} />)
      )}
    </div>
  )
}

function CouponsPage() {
  const [code, setCode] = useState('')
  const { data, isLoading, error, refetch } = trpc.user.coupon.getMyCoupons.useQuery()
  const redeemMutation = trpc.user.coupon.redeemReservedCoupon.useMutation({
    onSuccess: () => {
      setCode('')
      refetch()
    },
  })

  const personalCoupons = data?.data?.personal || []
  const generalCoupons = data?.data?.general || []

  const handleRedeem = () => {
    if (!code.trim() || code.trim().length < 4) return
    redeemMutation.mutate({ secretCode: code.trim().toUpperCase() })
  }

  if (isLoading) {
    return (
      <AppContainer>
        <div className="flex flex-1 items-center justify-center">
          <p className="text-gray-600">Loading coupons...</p>
        </div>
      </AppContainer>
    )
  }

  if (error) {
    return (
      <AppContainer>
        <div className="flex flex-1 flex-col items-center justify-center p-4">
          <AlertCircle className="mb-2 h-12 w-12 text-red-500" />
          <p className="text-center text-red-600">Failed to load coupons. Please try again.</p>
        </div>
      </AppContainer>
    )
  }

  return (
    <AppContainer>
      <div className="flex-1 p-4">
        {/* Add Coupon Card */}
        <div className="mb-6 rounded-lg border border-gray-100 bg-white p-4 shadow-sm">
          <p className="mb-3 text-lg font-semibold text-gray-800">Add a Coupon</p>
          <input
            type="text"
            placeholder="Enter coupon code"
            value={code}
            onChange={(e) => setCode(e.target.value)}
            className="mb-4 w-full rounded-lg border border-gray-200 px-4 py-2 text-sm focus:border-blue-500 focus:outline-none"
          />
          <button
            onClick={handleRedeem}
            disabled={redeemMutation.isPending || code.trim().length < 4}
            className={`w-full rounded-lg px-4 py-3 text-center font-semibold text-white ${
              redeemMutation.isPending || code.trim().length < 4
                ? 'cursor-not-allowed bg-gray-400 opacity-50'
                : 'bg-blue-500 hover:bg-blue-600'
            }`}
          >
            {redeemMutation.isPending ? 'Adding...' : 'Add Coupon'}
          </button>
        </div>

        {/* Coupon Sections */}
        <CouponSection
          title="Only for Me"
          coupons={personalCoupons}
          emptyMessage="No personal coupons available"
        />

        <CouponSection
          title="Apply to All"
          coupons={generalCoupons}
          emptyMessage="No general coupons available"
        />
      </div>
    </AppContainer>
  )
}
