"use client"

import { useState } from "react"
import { useMutation } from "convex/react"
import { toast } from "sonner"
import { api } from "../../../../../../convex/_generated/api"
import type { Id } from "../../../../../../convex/_generated/dataModel"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  ORDER_STATUS_CONFIG,
  type OrderStatus,
} from "../shared/statusConfig"

interface Props {
  orderId: Id<"orders">
  currentStatus: string
}

const ALL_STATUSES = Object.keys(ORDER_STATUS_CONFIG) as OrderStatus[]

export function UpdateStatusDialog({ orderId, currentStatus }: Props) {
  const [open, setOpen] = useState(false)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const availableStatuses = ALL_STATUSES.filter((s) => s !== currentStatus)
  const [selectedStatus, setSelectedStatus] = useState<string>(
    availableStatuses[0] ?? "",
  )

  const updateStatus = useMutation(api.orders.updateStatus)

  // Reset selection to first available when dialog opens
  function handleOpenChange(next: boolean) {
    if (next) {
      setSelectedStatus(availableStatuses[0] ?? "")
    }
    setOpen(next)
  }

  async function handleSubmit() {
    if (!selectedStatus) return
    setIsSubmitting(true)
    try {
      await updateStatus({
        id: orderId,
        status: selectedStatus as OrderStatus,
      })
      const label = ORDER_STATUS_CONFIG[selectedStatus as OrderStatus]?.label
      toast.success(`Status updated to ${label ?? selectedStatus}`)
      setOpen(false)
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : "Failed to update status.")
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <>
      <Button variant="outline" onClick={() => handleOpenChange(true)}>
        Update Status
      </Button>

      <Dialog open={open} onOpenChange={handleOpenChange}>
        <DialogContent showCloseButton={false}>
          <DialogHeader>
            <DialogTitle>Update order status</DialogTitle>
          </DialogHeader>

          <Select value={selectedStatus} onValueChange={setSelectedStatus}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder="Select a status" />
            </SelectTrigger>
            <SelectContent>
              {availableStatuses.map((s) => (
                <SelectItem key={s} value={s}>
                  {ORDER_STATUS_CONFIG[s].label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setOpen(false)}
              disabled={isSubmitting}
            >
              Cancel
            </Button>
            <Button
              onClick={handleSubmit}
              disabled={!selectedStatus || isSubmitting}
            >
              {isSubmitting && (
                <svg
                  data-icon="inline-start"
                  className="animate-spin"
                  viewBox="0 0 24 24"
                  fill="none"
                  aria-hidden="true"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  />
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                  />
                </svg>
              )}
              {isSubmitting ? "Updating…" : "Update"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  )
}
