"use client"

import { AlertTriangle } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Modal } from "@/components/ui/modal"
import { TextAreaField } from "@/components/ui/FormFields"
import { useState } from "react"
import type { WorkflowAction } from "./workflow-config"

type Props = {
  open: boolean
  action: WorkflowAction | null
  language: "ar" | "en"
  entityLabel?: string
  isSubmitting?: boolean
  onConfirm: (reason?: string) => void
  onClose: () => void
  children?: React.ReactNode
}

export function ActionModal({ open, action, language, entityLabel, isSubmitting, onConfirm, onClose, children }: Props) {
  const [reason, setReason] = useState("")

  if (!action) return null

  const isDanger = action.danger || action.variant === "danger"
  const needsReason = action.requireReason ?? false

  const handleConfirm = () => {
    if (needsReason && !reason.trim()) return
    onConfirm(needsReason ? reason.trim() : undefined)
    setReason("")
  }

  const handleClose = () => {
    setReason("")
    onClose()
  }

  return (
    <Modal
      open={open}
      onClose={handleClose}
      title={action.label[language]}
      description={entityLabel}
      size="sm"
    >
      <div className="space-y-4">
        {isDanger && (
          <div className="flex items-start gap-2 rounded-lg border border-red-200 bg-red-50 p-3 text-sm text-red-700">
            <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
            <span>
              {language === "ar"
                ? "هذا إجراء حساس ولا يمكن التراجع عنه. تأكد قبل المتابعة."
                : "This is a sensitive action and cannot be undone. Proceed with caution."}
            </span>
          </div>
        )}
        {children}
        {needsReason && (
          <TextAreaField
            id="action-reason"
            name="reason"
            label={language === "ar" ? "السبب" : "Reason"}
            required
            rows={3}
            value={reason}
            onChange={e => setReason(e.target.value)}
          />
        )}
        <div className="flex justify-end gap-2">
          <Button variant="outline" onClick={handleClose} disabled={isSubmitting}>
            {language === "ar" ? "إغلاق" : "Close"}
          </Button>
          <Button
            variant={isDanger ? "danger" : "primary"}
            onClick={handleConfirm}
            isLoading={isSubmitting}
          >
            {language === "ar" ? "تأكيد" : "Confirm"}
          </Button>
        </div>
      </div>
    </Modal>
  )
}