'use client'

import { useState } from 'react'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useCreateCustomer } from '@/hooks/use-customers'
import { Loader2, CheckCircle, AlertCircle, User, Mail, Building2 } from 'lucide-react'
import type { UserStatus } from '@/types/api'

interface AddCustomerDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSuccess?: (customerId: string) => void
}

type FormStep = 'form' | 'success' | 'error'

export function AddCustomerDialog({ open, onOpenChange, onSuccess }: AddCustomerDialogProps) {
  const [step, setStep] = useState<FormStep>('form')
  const [email, setEmail] = useState('')
  const [name, setName] = useState('')
  const [company, setCompany] = useState('')
  const [status, setStatus] = useState<UserStatus>('ACTIVE')
  const [errorMessage, setErrorMessage] = useState('')
  const [createdCustomerId, setCreatedCustomerId] = useState<string | null>(null)

  const createCustomer = useCreateCustomer()

  const resetForm = () => {
    setEmail('')
    setName('')
    setCompany('')
    setStatus('ACTIVE')
    setErrorMessage('')
    setCreatedCustomerId(null)
    setStep('form')
  }

  const handleClose = () => {
    resetForm()
    onOpenChange(false)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!email) {
      setErrorMessage('Email is required')
      return
    }

    // Basic email validation
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(email)) {
      setErrorMessage('Please enter a valid email address')
      return
    }

    try {
      const result = await createCustomer.mutateAsync({
        email,
        name: name || undefined,
        company: company || undefined,
        status,
      })

      setCreatedCustomerId(result.id)
      setStep('success')

      if (onSuccess) {
        onSuccess(result.id)
      }
    } catch (error) {
      setErrorMessage(
        error instanceof Error
          ? error.message
          : 'Failed to create customer. Please try again.'
      )
      setStep('error')
    }
  }

  const renderForm = () => (
    <form onSubmit={handleSubmit}>
      <DialogHeader>
        <DialogTitle>Add New Customer</DialogTitle>
        <DialogDescription>
          Create a new customer account. They will receive an email to set their password.
        </DialogDescription>
      </DialogHeader>

      <div className="space-y-4 py-4">
        {/* Email field */}
        <div className="space-y-2">
          <Label htmlFor="email" className="flex items-center gap-2">
            <Mail className="h-4 w-4" />
            Email <span className="text-red-500">*</span>
          </Label>
          <Input
            id="email"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="customer@example.com"
            required
          />
        </div>

        {/* Name field */}
        <div className="space-y-2">
          <Label htmlFor="name" className="flex items-center gap-2">
            <User className="h-4 w-4" />
            Name
          </Label>
          <Input
            id="name"
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="John Doe"
          />
        </div>

        {/* Company field */}
        <div className="space-y-2">
          <Label htmlFor="company" className="flex items-center gap-2">
            <Building2 className="h-4 w-4" />
            Company
          </Label>
          <Input
            id="company"
            type="text"
            value={company}
            onChange={(e) => setCompany(e.target.value)}
            placeholder="Acme Inc."
          />
        </div>

        {/* Status field */}
        <div className="space-y-2">
          <Label htmlFor="status">Initial Status</Label>
          <select
            id="status"
            value={status}
            onChange={(e) => setStatus(e.target.value as UserStatus)}
            className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          >
            <option value="ACTIVE">Active</option>
            <option value="PENDING_VERIFICATION">Pending Verification</option>
            <option value="SUSPENDED">Suspended</option>
          </select>
        </div>
      </div>

      <DialogFooter>
        <Button type="button" variant="outline" onClick={handleClose}>
          Cancel
        </Button>
        <Button type="submit" disabled={createCustomer.isPending}>
          {createCustomer.isPending ? (
            <>
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
              Creating...
            </>
          ) : (
            'Create Customer'
          )}
        </Button>
      </DialogFooter>
    </form>
  )

  const renderSuccess = () => (
    <>
      <DialogHeader>
        <DialogTitle className="flex items-center gap-2 text-green-600">
          <CheckCircle className="h-5 w-5" />
          Customer Created
        </DialogTitle>
        <DialogDescription>
          The customer account has been created successfully.
        </DialogDescription>
      </DialogHeader>

      <div className="py-6 text-center">
        <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-green-100">
          <CheckCircle className="h-8 w-8 text-green-600" />
        </div>
        <div className="space-y-1">
          <p className="font-medium">{name || email}</p>
          <p className="text-sm text-muted-foreground">{email}</p>
          {company && (
            <p className="text-sm text-muted-foreground">{company}</p>
          )}
        </div>
      </div>

      <DialogFooter>
        <Button variant="outline" onClick={resetForm}>
          Add Another
        </Button>
        <Button onClick={handleClose}>
          Done
        </Button>
      </DialogFooter>
    </>
  )

  const renderError = () => (
    <>
      <DialogHeader>
        <DialogTitle className="flex items-center gap-2 text-red-600">
          <AlertCircle className="h-5 w-5" />
          Error Creating Customer
        </DialogTitle>
        <DialogDescription>
          There was a problem creating the customer account.
        </DialogDescription>
      </DialogHeader>

      <div className="py-6 text-center">
        <div className="mb-4 inline-flex h-16 w-16 items-center justify-center rounded-full bg-red-100">
          <AlertCircle className="h-8 w-8 text-red-600" />
        </div>
        <p className="text-sm text-muted-foreground">{errorMessage}</p>
      </div>

      <DialogFooter>
        <Button variant="outline" onClick={handleClose}>
          Cancel
        </Button>
        <Button onClick={() => setStep('form')}>
          Try Again
        </Button>
      </DialogFooter>
    </>
  )

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        {step === 'form' && renderForm()}
        {step === 'success' && renderSuccess()}
        {step === 'error' && renderError()}
      </DialogContent>
    </Dialog>
  )
}
