"use client"

import { useState, useEffect } from "react"
import Link from "next/link"
import { supabase } from "@/lib/supabase"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import { Building2, ArrowLeft, Plus, Loader2 } from "lucide-react"

interface Business {
  business_id: number
  name: string
  slug: string
  created_at: string
}

async function getAuthHeaders(): Promise<HeadersInit> {
  const {
    data: { session },
  } = await supabase.auth.getSession()
  const headers: HeadersInit = { "Content-Type": "application/json" }
  if (session?.access_token) {
    (headers as Record<string, string>)["Authorization"] = `Bearer ${session.access_token}`
  }
  return headers
}

export default function AdminBusinessesPage() {
  const [list, setList] = useState<Business[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [createOpen, setCreateOpen] = useState(false)
  const [createName, setCreateName] = useState("")
  const [createSubmitting, setCreateSubmitting] = useState(false)

  const load = async () => {
    setLoading(true)
    setError("")
    try {
      const res = await fetch("/api/admin/businesses", {
        headers: await getAuthHeaders(),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data?.error || res.statusText)
      }
      const data = await res.json()
      setList(data)
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to load businesses")
      setList([])
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    load()
  }, [])

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!createName.trim()) return
    setCreateSubmitting(true)
    try {
      const res = await fetch("/api/admin/businesses", {
        method: "POST",
        headers: await getAuthHeaders(),
        body: JSON.stringify({ name: createName.trim() }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data?.error || res.statusText)
      }
      setCreateOpen(false)
      setCreateName("")
      load()
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to create business")
    } finally {
      setCreateSubmitting(false)
    }
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-slate-100 to-blue-50/30 dark:from-slate-950 dark:via-slate-900 dark:to-slate-800 p-4 sm:p-6">
      <div className="max-w-4xl mx-auto space-y-6">
        <div className="flex items-center gap-4">
          <Link href="/admin">
            <Button variant="outline" size="icon">
              <ArrowLeft className="h-4 w-4" />
            </Button>
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-slate-900 dark:text-white flex items-center gap-2">
              <Building2 className="h-7 w-7" />
              Businesses
            </h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">
              Manage businesses and view data by business.
            </p>
          </div>
          <Button onClick={() => setCreateOpen(true)} className="ml-auto" size="default">
            <Plus className="h-4 w-4 mr-2" />
            Add business
          </Button>
        </div>

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

        <Card>
          <CardHeader>
            <CardTitle>All businesses</CardTitle>
            <CardDescription>Create and list businesses. Use Authorizations to assign users.</CardDescription>
          </CardHeader>
          <CardContent>
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <Loader2 className="h-8 w-8 animate-spin text-slate-400" />
              </div>
            ) : list.length === 0 ? (
              <p className="text-slate-500 dark:text-slate-400 py-8 text-center">
                No businesses yet. Add one to get started.
              </p>
            ) : (
              <ul className="divide-y divide-slate-200 dark:divide-slate-700">
                {list.map((b) => (
                  <li
                    key={b.business_id}
                    className="py-3 flex items-center justify-between gap-4"
                  >
                    <div>
                      <span className="font-medium text-slate-900 dark:text-white">{b.name}</span>
                      <span className="text-slate-500 dark:text-slate-400 ml-2 text-sm">({b.slug})</span>
                    </div>
                    <span className="text-xs text-slate-400 dark:text-slate-500">
                      ID: {b.business_id}
                    </span>
                  </li>
                ))}
              </ul>
            )}
          </CardContent>
        </Card>
      </div>

      <Dialog open={createOpen} onOpenChange={setCreateOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add business</DialogTitle>
            <DialogDescription>Create a new business. Slug is generated from the name.</DialogDescription>
          </DialogHeader>
          <form onSubmit={handleCreate}>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label htmlFor="business-name">Name</Label>
                <Input
                  id="business-name"
                  value={createName}
                  onChange={(e) => setCreateName(e.target.value)}
                  placeholder="Acme Inc"
                  disabled={createSubmitting}
                />
              </div>
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setCreateOpen(false)} disabled={createSubmitting}>
                Cancel
              </Button>
              <Button type="submit" disabled={createSubmitting || !createName.trim()}>
                {createSubmitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
                Create
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  )
}
