"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Dropdown } from "@/components/ui/dropdown"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

type Branch = { id: string; name: string }

export default function DepartmentForm({ branches }: { branches: Branch[] }) {
  const router = useRouter()

  const [name, setName] = useState("")
  const [branchId, setBranchId] = useState("")
  const [subDepartmentName, setSubDepartmentName] = useState("")
  const [subDepartments, setSubDepartments] = useState<string[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState("")

  const branchOptions = branches.map((b) => ({ value: b.id, label: b.name }))

  function addSubDepartment() {
    const v = subDepartmentName.trim()
    if (!v) return
    setSubDepartments((prev) => [...prev, v])
    setSubDepartmentName("")
  }

  function removeSubDepartment(idx: number) {
    setSubDepartments((prev) => prev.filter((_, i) => i !== idx))
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!branchId) {
      setError("Please select a branch")
      return
    }
    setLoading(true)
    setError("")

    try {
      const res = await fetch("/api/departments", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name,
          branchId,
          subDepartments: subDepartments.map((n) => ({ name: n })),
        }),
      })

      if (!res.ok) {
        const data = await res.json().catch(() => null)
        throw new Error(data?.error || "Failed to create department")
      }

      router.push("/departments")
      router.refresh()
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : "Failed to create department")
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive">
          {error}
        </div>
      )}

      <div className="flex items-center justify-end">
        <Button type="submit" disabled={loading}>
          {loading ? "Saving..." : "Save"}
        </Button>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-sm font-medium">Department</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          <Dropdown
            label="Branch *"
            placeholder="Select branch…"
            searchPlaceholder="Search branches…"
            options={branchOptions}
            value={branchId}
            onChange={setBranchId}
            emptyMessage="No branches found."
          />

          <div className="space-y-2">
            <Label>Name</Label>
            <Input
              value={name}
              onChange={(e) => setName(e.target.value)}
              required
              placeholder="e.g. Cardiology"
            />
          </div>

          <div className="space-y-2">
            <Label>Sub Departments (optional)</Label>
            <div className="flex gap-2">
              <Input
                value={subDepartmentName}
                onChange={(e) => setSubDepartmentName(e.target.value)}
                placeholder="e.g. Pediatric Cardiology"
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault()
                    addSubDepartment()
                  }
                }}
              />
              <Button type="button" variant="secondary" onClick={addSubDepartment}>
                Add
              </Button>
            </div>

            <div className="space-y-2">
              {subDepartments.length === 0 ? (
                <div className="text-sm text-muted-foreground">No sub departments added</div>
              ) : (
                subDepartments.map((sd, idx) => (
                  <div
                    key={`${sd}-${idx}`}
                    className="flex items-center justify-between rounded-md border p-2"
                  >
                    <span className="text-sm">{sd}</span>
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      onClick={() => removeSubDepartment(idx)}
                    >
                      Remove
                    </Button>
                  </div>
                ))
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    </form>
  )
}