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

export const Route = createFileRoute('/me/addresses')({ component: AddressesPage })

function AddressesPage() {
  const utils = trpc.useUtils()
  const { data } = trpc.user.address.getUserAddresses.useQuery()
  const deleteMutation = trpc.user.address.deleteAddress.useMutation({
    onSuccess: () => utils.user.address.getUserAddresses.invalidate(),
  })
  const addresses = data?.data || []

  return (
    <AppContainer>
      <p className="font-bold mb-4 text-xl">
        My Addresses
      </p>

      {addresses.length === 0 ? (
        <div className="flex flex-col items-center gap-4 py-20">
          <MapPin className="h-12 w-12 text-gray-300" />
          <p className="text-gray-500">No addresses saved</p>
        </div>
      ) : (
        <div className="flex flex-col gap-3">
          {addresses.map((addr: any) => (
            <div
              key={addr.id}
              className="rounded-xl border border-gray-100 bg-white p-4 shadow-sm"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <p className="font-semibold">{addr.name}</p>
                  <p className="text-sm text-gray-600">
                    {addr.addressLine1}
                    {addr.addressLine2 ? `, ${addr.addressLine2}` : ''}
                  </p>
                  <p className="text-sm text-gray-600">
                    {addr.city}, {addr.state} - {addr.pincode}
                  </p>
                  <p className="text-sm text-gray-500">{addr.phone}</p>
                  {addr.isDefault && (
                    <span className="mt-1 inline-block rounded-full bg-brand-100 px-2 py-0.5 text-xs text-brand-700">
                      Default
                    </span>
                  )}
                </div>
                <button
                  onClick={() => deleteMutation.mutate({ id: addr.id })}
                  className="text-sm text-red-500 hover:text-red-700"
                >
                  Delete
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </AppContainer>
  )
}
