"use client"

import { useState, useEffect, use } from "react"
import { useRouter } from "next/navigation"

export default function EditTeamPage({ params }: { params: Promise<{ id: string }> }) {
  const router = useRouter()
  const { id } = use(params)
  const [loading, setLoading] = useState(false)
  const [managers, setManagers] = useState<any[]>([])
  const [formData, setFormData] = useState({
    name: "",
    shiftManagerId: ""
  })
  const [originalManagerId, setOriginalManagerId] = useState("")
  const [error, setError] = useState("")

  useEffect(() => {
    // Fetch managers with their teams
    fetch("/api/admin/managers-with-teams")
      .then(r => r.json())
      .then(setManagers)
    
    fetch(`/api/admin/teams/${id}`)
      .then(r => r.json())
      .then(data => {
        setFormData(data)
        setOriginalManagerId(data.shiftManagerId)
      })
  }, [id])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError("")
    
    // Only check if manager changed
    if (formData.shiftManagerId !== originalManagerId) {
      // Check if selected manager already has a team
      const selectedManager = managers.find(m => m.id === formData.shiftManagerId)
      if (selectedManager && selectedManager.teams && selectedManager.teams.length > 0) {
        setError(`This manager is already assigned to: ${selectedManager.teams.map((t: any) => t.name).join(", ")}`)
        return
      }
    }

    setLoading(true)

    const response = await fetch(`/api/admin/teams/${id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(formData)
    })

    if (response.ok) {
      router.push("/admin/teams")
    } else {
      setError("Error updating team")
      setLoading(false)
    }
  }

  const handleDelete = async () => {
    if (!confirm("Are you sure you want to delete this team?")) return

    const response = await fetch(`/api/admin/teams/${id}`, {
      method: "DELETE"
    })

    if (response.ok) {
      router.push("/admin/teams")
    } else {
      alert("Error deleting team")
    }
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-2xl mx-auto">
        <h1 className="text-3xl font-bold text-gray-800 mb-6">Edit Team</h1>

        <form onSubmit={handleSubmit} className="bg-white p-6 rounded-xl shadow-sm border border-gray-200 space-y-4">
          <div>
            <label className="block text-sm font-medium mb-2">Team Name *</label>
            <input
              type="text"
              value={formData.name}
              onChange={(e) => setFormData({...formData, name: e.target.value})}
              className="w-full px-4 py-2 border rounded-lg"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium mb-2">Shift Manager *</label>
            <select
              value={formData.shiftManagerId}
              onChange={(e) => {
                setFormData({...formData, shiftManagerId: e.target.value})
                setError("")
              }}
              className="w-full px-4 py-2 border rounded-lg"
              required
            >
              <option value="">Select Manager</option>
              {managers.map((manager: any) => (
                <option key={manager.id} value={manager.id}>
                  {manager.firstName} {manager.surname} ({manager.empNo})
                  {manager.teams && manager.teams.length > 0 && manager.id !== originalManagerId && ` - Already assigned to: ${manager.teams.map((t: any) => t.name).join(", ")}`}
                </option>
              ))}
            </select>
          </div>

          {error && (
            <div className="bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
              {error}
            </div>
          )}

          <div className="flex gap-4 pt-4">
            <button
              type="submit"
              disabled={loading}
              className="flex-1 bg-blue-600 text-white py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:opacity-50"
            >
              {loading ? "Updating..." : "Update Team"}
            </button>
            <button
              type="button"
              onClick={() => router.back()}
              className="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50"
            >
              Cancel
            </button>
            <button
              type="button"
              onClick={handleDelete}
              className="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700"
            >
              Delete
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
