'use client'

import { useState } from 'react'
import { StaffRole } from '@prisma/client'
import { useInviteStaff } from '@/hooks/use-staff'
import { getAssignableRoles } from '@/lib/services/permission-service'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { Copy, Check, Mail } from 'lucide-react'

interface InviteStaffDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  currentRole: StaffRole
}

const roleDescriptions: Record<StaffRole, string> = {
  OWNER: 'Full access including deleting staff members',
  ADMIN: 'Full access to all features except deleting staff',
  MANAGER: 'Manage orders, customers, and servers',
  SUPPORT: 'View-only access to orders and customers',
}

export function InviteStaffDialog({
  open,
  onOpenChange,
  currentRole,
}: InviteStaffDialogProps) {
  const [email, setEmail] = useState('')
  const [role, setRole] = useState<StaffRole>('SUPPORT')
  const [inviteUrl, setInviteUrl] = useState<string | null>(null)
  const [emailSent, setEmailSent] = useState<boolean | null>(null)
  const [copied, setCopied] = useState(false)

  const inviteStaff = useInviteStaff()
  const assignableRoles = getAssignableRoles(currentRole)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const result = await inviteStaff.mutateAsync({ email, role })
      setInviteUrl(result.inviteUrl)
      setEmailSent(result.emailSent ?? false)
    } catch {
      // Error handled by mutation
    }
  }

  const handleCopyUrl = async () => {
    if (!inviteUrl) return
    await navigator.clipboard.writeText(inviteUrl)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  const handleClose = () => {
    setEmail('')
    setRole('SUPPORT')
    setInviteUrl(null)
    setEmailSent(null)
    setCopied(false)
    inviteStaff.reset()
    onOpenChange(false)
  }

  return (
    <Dialog open={open} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>
            {inviteUrl ? 'Invitation Sent' : 'Invite Staff Member'}
          </DialogTitle>
          <DialogDescription>
            {inviteUrl
              ? 'Share this link with the new team member to complete registration.'
              : 'Send an invitation to add a new team member.'}
          </DialogDescription>
        </DialogHeader>

        {inviteUrl ? (
          <div className="space-y-4">
            <div className="flex items-center gap-2">
              <Mail className={`h-5 w-5 ${emailSent ? 'text-green-600' : 'text-amber-600'}`} />
              <span className="text-sm font-medium">
                {emailSent
                  ? `Invitation email sent to ${email}`
                  : `Invitation created for ${email}`}
              </span>
            </div>

            {!emailSent && (
              <p className="text-sm text-amber-600 bg-amber-50 p-3 rounded-md">
                Email could not be sent. Please share the link below manually.
              </p>
            )}

            <div className="space-y-2">
              <Label>Invitation Link</Label>
              <div className="flex gap-2">
                <Input
                  value={inviteUrl}
                  readOnly
                  className="font-mono text-xs"
                />
                <Button
                  type="button"
                  variant="outline"
                  size="icon"
                  onClick={handleCopyUrl}
                >
                  {copied ? (
                    <Check className="h-4 w-4 text-green-600" />
                  ) : (
                    <Copy className="h-4 w-4" />
                  )}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground">
                This link expires in 7 days
              </p>
            </div>

            <DialogFooter>
              <Button onClick={handleClose}>Done</Button>
            </DialogFooter>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="email">Email Address</Label>
              <Input
                id="email"
                type="email"
                placeholder="colleague@company.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
              />
            </div>

            <div className="space-y-2">
              <Label htmlFor="role">Role</Label>
              <Select
                value={role}
                onValueChange={(value) => setRole(value as StaffRole)}
              >
                <SelectTrigger>
                  <SelectValue placeholder="Select a role" />
                </SelectTrigger>
                <SelectContent>
                  {assignableRoles.map((r) => (
                    <SelectItem key={r} value={r}>
                      <div className="flex flex-col">
                        <span>{r}</span>
                      </div>
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <p className="text-xs text-muted-foreground">
                {roleDescriptions[role]}
              </p>
            </div>

            {inviteStaff.error && (
              <p className="text-sm text-red-500">
                {inviteStaff.error.message}
              </p>
            )}

            <DialogFooter>
              <Button
                type="button"
                variant="outline"
                onClick={handleClose}
              >
                Cancel
              </Button>
              <Button type="submit" disabled={inviteStaff.isPending}>
                {inviteStaff.isPending ? 'Sending...' : 'Send Invitation'}
              </Button>
            </DialogFooter>
          </form>
        )}
      </DialogContent>
    </Dialog>
  )
}
