import React, { useState } from 'react'
import { trpc } from '../lib/trpc-client'
import { p, pInput, MyButton, div } from 'web-components'
import { MapPin, X, Plus } from 'lucide-react'
import * as Yup from 'yup'

interface AddressFormProps {
  onSuccess: (addressId?: number) => void
  initialValues?: {
    id?: number
    name: string
    phone: string
    addressLine1: string
    addressLine2: string
    city: string
    state: string
    pincode: string
    isDefault: boolean
    latitude?: number
    longitude?: number
    googleMapsUrl?: string
  }
  isEdit?: boolean
}

const validationSchema = Yup.object({
  name: Yup.string().required('Name is required'),
  phone: Yup.string().required('Phone is required').matches(/^\d{10}$/, 'Phone must be 10 digits'),
  addressLine1: Yup.string().required('Address Line 1 is required'),
  addressLine2: Yup.string(),
  city: Yup.string().required('City is required'),
  state: Yup.string().required('State is required'),
  pincode: Yup.string().required('Pincode is required').matches(/^\d{6}$/, 'Pincode must be 6 digits'),
  isDefault: Yup.boolean(),
})

export function AddressForm({ onSuccess, initialValues, isEdit = false }: AddressFormProps) {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [submitError, setSubmitError] = useState<string | null>(null)
  const [showGoogleMapsField, setShowGoogleMapsField] = useState(!!initialValues?.googleMapsUrl)
  const [currentLocation, setCurrentLocation] = useState<{ latitude: number; longitude: number } | null>(
    initialValues?.latitude && initialValues?.longitude
      ? { latitude: initialValues.latitude, longitude: initialValues.longitude }
      : null
  )

  const [values, setValues] = useState({
    name: initialValues?.name || '',
    phone: initialValues?.phone || '',
    addressLine1: initialValues?.addressLine1 || '',
    addressLine2: initialValues?.addressLine2 || '',
    city: initialValues?.city || 'Mahabubnagar',
    state: initialValues?.state || 'Telangana',
    pincode: initialValues?.pincode || '509001',
    isDefault: initialValues?.isDefault || false,
    googleMapsUrl: initialValues?.googleMapsUrl || '',
  })

  const [errors, setErrors] = useState<Record<string, string>>({})

  const createMutation = trpc.user.address.createAddress.useMutation({
    onSuccess: (data) => {
      setIsSubmitting(false)
      onSuccess(data?.data?.id)
    },
    onError: (error: any) => {
      setIsSubmitting(false)
      setSubmitError(error.message || 'Failed to save address')
    },
  })

  const updateMutation = trpc.user.address.updateAddress.useMutation({
    onSuccess: () => {
      setIsSubmitting(false)
      onSuccess()
    },
    onError: (error: any) => {
      setIsSubmitting(false)
      setSubmitError(error.message || 'Failed to update address')
    },
  })

  const handleChange = (field: string, value: string | boolean) => {
    setValues((prev) => ({ ...prev, [field]: value }))
    if (errors[field]) {
      setErrors((prev) => ({ ...prev, [field]: '' }))
    }
  }

  const handleSubmit = async () => {
    try {
      await validationSchema.validate(values, { abortEarly: false })
      setIsSubmitting(true)
      setSubmitError(null)

      const payload = {
        ...values,
        latitude: currentLocation?.latitude,
        longitude: currentLocation?.longitude,
        googleMapsUrl: values.googleMapsUrl || undefined,
      }

      if (isEdit && initialValues?.id) {
        updateMutation.mutate({ id: initialValues.id, ...payload })
      } else {
        createMutation.mutate(payload)
      }
    } catch (err: any) {
      const validationErrors: Record<string, string> = {}
      err.inner?.forEach((error: any) => {
        validationErrors[error.path] = error.message
      })
      setErrors(validationErrors)
    }
  }

  return (
    <div className="max-h-[80vh] overflow-y-auto p-6">
      <div className="mb-6 flex items-center justify-between">
        <p className="font-bold text-xl">
          {isEdit ? 'Edit Address' : 'Add Address'}
        </p>
      </div>

      {/* Service Area Notice */}
      <div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 p-3">
        <div className="flex items-center gap-2">
          <span className="text-amber-600">ℹ️</span>
          <p className="flex-1 text-sm text-amber-800">
            We currently serve only in Mahabubnagar town
          </p>
        </div>
      </div>

      {/* Submit Error Message */}
      {submitError && (
        <div className="mb-4 rounded-lg border border-red-200 bg-red-50 p-3">
          <p className="text-sm text-red-600">{submitError}</p>
        </div>
      )}

      <div className="space-y-4">
        <div>
          <pInput
            placeholder="Name"
            value={values.name}
            onChange={(e) => handleChange('name', e.target.value)}
            className={errors.name ? 'border-red-500' : ''}
          />
          {errors.name && <p className="mt-1 text-sm text-red-500">{errors.name}</p>}
        </div>

        <div>
          <pInput
            placeholder="Phone"
            type="tel"
            value={values.phone}
            onChange={(e) => handleChange('phone', e.target.value)}
            className={errors.phone ? 'border-red-500' : ''}
          />
          {errors.phone && <p className="mt-1 text-sm text-red-500">{errors.phone}</p>}
        </div>

        <div>
          <pInput
            placeholder="Address Line 1"
            value={values.addressLine1}
            onChange={(e) => handleChange('addressLine1', e.target.value)}
            className={errors.addressLine1 ? 'border-red-500' : ''}
          />
          {errors.addressLine1 && <p className="mt-1 text-sm text-red-500">{errors.addressLine1}</p>}
        </div>

        <div>
          <pInput
            placeholder="Address Line 2 (Optional)"
            value={values.addressLine2}
            onChange={(e) => handleChange('addressLine2', e.target.value)}
          />
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <pInput
              placeholder="City"
              value={values.city}
              disabled
              className="bg-gray-100"
            />
          </div>
          <div>
            <pInput
              placeholder="State"
              value={values.state}
              disabled
              className="bg-gray-100"
            />
          </div>
        </div>

        <div>
          <pInput
            placeholder="Pincode"
            value={values.pincode}
            disabled
            className="bg-gray-100"
          />
        </div>

        {!showGoogleMapsField && (
          <div
            onClick={() => setShowGoogleMapsField(true)}
            className="text-blue-500"
          >
            <p className="font-medium text-sm">
              Attach with Google Maps
            </p>
          </div>
        )}

        {showGoogleMapsField && (
          <div className="space-y-2">
            <p className="text-xs text-gray-500">
              1. Open Google Maps and Find location<br />
              2. Long press the desired location<br />
              3. Click on Share and Click on Copy<br />
              4. Paste the copied url here in the field.
            </p>
            <pInput
              placeholder="Google Maps Shared URL"
              value={values.googleMapsUrl}
              onChange={(e) => handleChange('googleMapsUrl', e.target.value)}
            />
          </div>
        )}

        <label className="flex cursor-pointer items-center gap-2">
          <input
            type="checkbox"
            checked={values.isDefault}
            onChange={(e) => handleChange('isDefault', e.target.checked)}
            className="h-4 w-4 rounded border-gray-300 text-brand-500 focus:ring-brand-500"
          />
          <p>Set as default address</p>
        </label>

        <MyButton
          fullWidth
          textContent={isSubmitting ? (isEdit ? 'Updating...' : 'Adding...') : (isEdit ? 'Update Address' : 'Add Address')}
          onClick={handleSubmit}
          disabled={isSubmitting}
          className="bg-brand-500 text-white"
        />
      </div>
    </div>
  )
}
