import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { useAuth } from '../lib/auth-context'
import { trpc } from '../lib/trpc-client'
import { p, AppContainer, div } from 'web-components'
import { AlertCircle, LogOut, Trash2, User, Mail, Phone, X } from 'lucide-react'
import { Dialog } from '../components/Dialog'

export const Route = createFileRoute('/me/edit-profile')({ component: EditProfilePage })

function EditProfilePage() {
  const navigate = useNavigate()
  const { user, logout, loginWithToken } = useAuth()
  const [name, setName] = useState(user?.name || '')
  const [email, setEmail] = useState(user?.email || '')
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [enteredMobile, setEnteredMobile] = useState('')

  const updateMutation = trpc.user.auth.updateProfile.useMutation({
    onSuccess: (data) => {
      if (data.data.token && data.data.user) {
        loginWithToken(data.data.token, data.data.user)
      }
      navigate({ to: '/me' })
    },
  })

  const deleteMutation = trpc.user.auth.deleteAccount.useMutation({
    onSuccess: () => {
      setShowDeleteModal(false)
      logout()
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    updateMutation.mutate({ name, email })
  }

  const handleDeleteAccount = () => {
    setShowDeleteModal(true)
  }

  const confirmDeleteAccount = () => {
    if (!enteredMobile.trim()) {
      alert('Please enter your mobile number')
      return
    }
    deleteMutation.mutate({ mobile: enteredMobile.trim() })
  }

  return (
    <AppContainer>
      <div className="flex min-h-full flex-col px-4 py-8">
        {/* Header */}
        <div className="mb-8 mt-4 text-center">
          <p className="mb-2 text-3xl font-bold text-gray-800">Edit Profile</p>
          <p className="text-base text-gray-600">Update your account details</p>
        </div>

        {/* Profile Form */}
        <form onSubmit={handleSubmit} className="flex flex-col gap-4">
          {/* Name Field */}
          <div className="rounded-lg border border-gray-100 bg-white p-4 shadow-sm">
            <label className="mb-2 flex items-center gap-2 text-sm font-medium text-gray-700">
              <User className="h-4 w-4" />
              Full Name
            </label>
            <input
              type="text"
              placeholder="Enter your name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none"
            />
          </div>

          {/* Email Field */}
          <div className="rounded-lg border border-gray-100 bg-white p-4 shadow-sm">
            <label className="mb-2 flex items-center gap-2 text-sm font-medium text-gray-700">
              <Mail className="h-4 w-4" />
              Email Address
            </label>
            <input
              type="email"
              placeholder="Enter your email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="w-full rounded-lg border border-gray-200 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none"
            />
          </div>

          {/* Mobile Field (Disabled) */}
          <div className="rounded-lg border border-gray-100 bg-white p-4 shadow-sm">
            <label className="mb-2 flex items-center gap-2 text-sm font-medium text-gray-700">
              <Phone className="h-4 w-4" />
              Mobile Number
            </label>
            <input
              type="tel"
              value={user?.mobile || ''}
              disabled
              className="w-full cursor-not-allowed rounded-lg border border-gray-200 bg-gray-50 px-4 py-3 text-sm text-gray-500"
            />
            <p className="mt-1 text-xs text-gray-400">Mobile number cannot be changed</p>
          </div>

          {/* Save Button */}
          <button
            type="submit"
            disabled={updateMutation.isPending}
            className={`mt-2 w-full rounded-lg px-4 py-3 font-semibold text-white transition-colors ${
              updateMutation.isPending
                ? 'cursor-not-allowed bg-gray-400'
                : 'bg-blue-600 hover:bg-blue-700'
            }`}
          >
            {updateMutation.isPending ? 'Saving...' : 'Save Changes'}
          </button>
        </form>

        {/* Action Buttons */}
        <div className="mt-8 space-y-3">
          {/* Logout Button */}
          <button
            onClick={logout}
            className="flex w-full items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-3 font-medium text-red-600 transition-colors hover:bg-red-50"
          >
            <LogOut className="h-4 w-4" />
            Logout
          </button>

          {/* Delete Account Button */}
          <button
            onClick={handleDeleteAccount}
            className="flex w-full items-center justify-center gap-2 rounded-lg bg-red-600 px-4 py-3 font-medium text-white transition-colors hover:bg-red-700"
          >
            <Trash2 className="h-4 w-4" />
            Delete Me and My Data
          </button>
        </div>
      </div>

      {/* Delete Account Modal */}
      <Dialog open={showDeleteModal} onClose={() => setShowDeleteModal(false)}>
        <div className="p-4">
          <div className="mb-4 flex items-center justify-between">
            <div className="flex items-center gap-2 text-red-600">
              <AlertCircle className="h-6 w-6" />
              <p className="text-xl font-bold">Delete Account Permanently</p>
            </div>
            <button
              onClick={() => setShowDeleteModal(false)}
              className="rounded-full p-1 hover:bg-gray-100"
            >
              <X className="h-5 w-5 text-gray-500" />
            </button>
          </div>

          <p className="mb-4 text-center text-gray-700">
            This action cannot be undone. All your data will be permanently deleted.
          </p>

          <p className="mb-4 text-sm text-gray-600">
            Enter your registered mobile number to confirm:
          </p>

          <div className="mb-6">
            <input
              type="tel"
              value={enteredMobile}
              onChange={(e) => setEnteredMobile(e.target.value)}
              placeholder="Enter mobile number"
              className="w-full rounded-lg border border-gray-300 px-4 py-3 text-sm focus:border-red-500 focus:outline-none"
              maxLength={15}
            />
          </div>

          <div className="flex gap-3">
            <button
              onClick={() => setShowDeleteModal(false)}
              className="flex-1 rounded-lg border border-gray-200 bg-gray-100 px-4 py-3 font-medium text-gray-700 transition-colors hover:bg-gray-200"
            >
              Cancel
            </button>
            <button
              onClick={confirmDeleteAccount}
              disabled={deleteMutation.isPending || !enteredMobile.trim()}
              className={`flex-1 rounded-lg px-4 py-3 font-medium text-white transition-colors ${
                deleteMutation.isPending || !enteredMobile.trim()
                  ? 'cursor-not-allowed bg-red-400'
                  : 'bg-red-600 hover:bg-red-700'
              }`}
            >
              {deleteMutation.isPending ? 'Deleting...' : 'Delete Forever'}
            </button>
          </div>
        </div>
      </Dialog>
    </AppContainer>
  )
}
