"use client"

import { useState } from "react"
import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { UpdateButton } from "@/components/update-button"
import { Terminal } from "lucide-react"
import { RoomSelectDialog } from "@/components/room-select-dialog"

interface FormSubmitTemplateProps {
  title: string
  description: string
  isLoading?: boolean
  children: (props: {
    command: string
    setCommand: (val: string) => void
  }) => React.ReactNode
  onSubmit?: (roomName: string, command: string) => void
  submitLoading?: boolean
  rooms?: string[]
}

export function FormSubmitTemplate({
  title,
  description,
  isLoading,
  children,
  onSubmit,
  submitLoading,
  rooms = [],
}: FormSubmitTemplateProps) {
  const [dialogOpen, setDialogOpen] = useState(false)
  const [command, setCommand] = useState("")

  const handleClick = () => {
    if (rooms.length > 0 && onSubmit) {
      setDialogOpen(true)
    }
  }

  return (
    <div className="w-full px-6 space-y-4">
      <div>
        <h1 className="text-3xl font-bold">{title}</h1>
        <p className="text-muted-foreground mt-2">{description}</p>
      </div>

      <Card className="w-full">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Terminal className="h-5 w-5" /> Gửi lệnh CMD
          </CardTitle>
          <CardDescription>Nhập và gửi lệnh xuống thiết bị</CardDescription>
        </CardHeader>
        <CardContent>
          {children({ command, setCommand })}
        </CardContent>

        {onSubmit && (
          <CardFooter className="flex gap-2">
            <UpdateButton
              onClick={handleClick}
              loading={submitLoading}
              label="Yêu cầu theo phòng"
            />
            <UpdateButton
              onClick={() => onSubmit("All", command)}
              loading={submitLoading}
              label="Cập nhật tất cả thiết bị"
            />
          </CardFooter>
        )}
      </Card>

      {onSubmit && rooms.length > 0 && (
        <RoomSelectDialog
          open={dialogOpen}
          onClose={() => setDialogOpen(false)}
          rooms={rooms}
          onConfirm={(roomName) => {
            onSubmit(roomName, command)
            setDialogOpen(false)
          }}
        />
      )}
    </div>
  )
}
