"use client"

import { useState, useEffect, useCallback } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import { Shield, ArrowLeft, Plus, Loader2, Search, Trash2 } from "lucide-react"

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

interface AuthorizationRow {
  id: number
  business_id: number
  user_id: number
  authorized_by_admin_id: number
  account_identifier: string | null
  notes: string | null
  created_at: string
  business_name: string | null
  business_slug: string | null
  user_name: string | null
  user_email: string | null
  authorized_by_name: string | null
  authorized_by_email: string | null
}

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 AdminAuthorizationsPage() {
  const [businesses, setBusinesses] = useState<Business[]>([])
  const [list, setList] = useState<AuthorizationRow[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState("")
  const [filterBusinessId, setFilterBusinessId] = useState<string>("")
  const [addOpen, setAddOpen] = useState(false)
  const [addBusinessId, setAddBusinessId] = useState("")
  const [lookupInput, setLookupInput] = useState("")
  const [lookupMode, setLookupMode] = useState<"email" | "username">("email")
  const [lookupResult, setLookupResult] = useState<{
    found: boolean
    user?: { user_id: number; user_name: string; email: string }
  } | null>(null)
  const [lookupLoading, setLookupLoading] = useState(false)
  const [addUserId, setAddUserId] = useState<number | null>(null)
  const [addSubmitting, setAddSubmitting] = useState(false)
  const [revokeId, setRevokeId] = useState<number | null>(null)

  const loadBusinesses = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/businesses", { headers: await getAuthHeaders() })
      if (res.ok) {
        const data = await res.json()
        setBusinesses(data)
      }
    } catch {
      setBusinesses([])
    }
  }, [])

  const loadList = useCallback(async () => {
    setLoading(true)
    setError("")
    try {
      const params = new URLSearchParams()
      if (filterBusinessId) params.set("business_id", filterBusinessId)
      const res = await fetch(`/api/admin/authorizations?${params}`, {
        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 authorizations")
      setList([])
    } finally {
      setLoading(false)
    }
  }, [filterBusinessId])

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

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

  const handleLookup = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!lookupInput.trim()) return
    setLookupLoading(true)
    setLookupResult(null)
    try {
      const param = lookupMode === "email" ? `email=${encodeURIComponent(lookupInput.trim())}` : `username=${encodeURIComponent(lookupInput.trim())}`
      const res = await fetch(`/api/admin/users/lookup?${param}`, {
        headers: await getAuthHeaders(),
      })
      const data = await res.json()
      if (res.status === 404) {
        setLookupResult({ found: false })
      } else if (res.ok && data.found && data.user) {
        setLookupResult({ found: true, user: data.user })
      } else {
        setLookupResult({ found: false })
      }
    } catch {
      setLookupResult({ found: false })
    } finally {
      setLookupLoading(false)
    }
  }

  const handleAddAuthorization = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!addBusinessId || addUserId == null) return
    setAddSubmitting(true)
    try {
      const res = await fetch("/api/admin/authorizations", {
        method: "POST",
        headers: await getAuthHeaders(),
        body: JSON.stringify({ business_id: Number(addBusinessId), user_id: addUserId }),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data?.error || res.statusText)
      }
      setAddOpen(false)
      setAddBusinessId("")
      setAddUserId(null)
      setLookupResult(null)
      setLookupInput("")
      loadList()
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to add authorization")
    } finally {
      setAddSubmitting(false)
    }
  }

  const handleRevoke = async (id: number) => {
    if (!confirm("Revoke this authorization?")) return
    setRevokeId(id)
    try {
      const res = await fetch(`/api/admin/authorizations/${id}`, {
        method: "DELETE",
        headers: await getAuthHeaders(),
      })
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data?.error || res.statusText)
      }
      loadList()
    } catch (e) {
      setError(e instanceof Error ? e.message : "Failed to revoke")
    } finally {
      setRevokeId(null)
    }
  }

  const openAddWithUser = (user: { user_id: number; user_name: string; email: string }) => {
    setAddUserId(user.user_id)
    setLookupResult({ found: true, user })
    setAddOpen(true)
  }

  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-6xl 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">
              <Shield className="h-7 w-7" />
              Authorization checklist
            </h1>
            <p className="text-sm text-slate-500 dark:text-slate-400 mt-0.5">
              Manage who is authorized for which business. Look up users and grant or revoke access.
            </p>
          </div>
          <Button onClick={() => setAddOpen(true)} className="ml-auto" size="default">
            <Plus className="h-4 w-4 mr-2" />
            Add authorization
          </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>
        )}

        {/* User lookup */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Search className="h-5 w-5" />
              Check user exists
            </CardTitle>
            <CardDescription>Look up by email or username to see if a user exists. You can then add them to the authorization list.</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleLookup} className="flex flex-wrap items-end gap-3">
              <div className="flex-1 min-w-[200px] space-y-2">
                <Label>Email or username</Label>
                <Input
                  value={lookupInput}
                  onChange={(e) => setLookupInput(e.target.value)}
                  placeholder={lookupMode === "email" ? "user@example.com" : "username"}
                  disabled={lookupLoading}
                />
              </div>
              <div className="space-y-2">
                <Label className="opacity-0">Mode</Label>
                <Select value={lookupMode} onValueChange={(v: "email" | "username") => setLookupMode(v)}>
                  <SelectTrigger className="w-[120px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="email">Email</SelectItem>
                    <SelectItem value="username">Username</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Button type="submit" disabled={lookupLoading || !lookupInput.trim()}>
                {lookupLoading ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
                Look up
              </Button>
            </form>
            {lookupResult !== null && (
              <div className="mt-4 p-4 rounded-lg border bg-slate-50 dark:bg-slate-900/50">
                {lookupResult.found && lookupResult.user ? (
                  <div className="flex flex-wrap items-center justify-between gap-4">
                    <div>
                      <p className="font-medium text-green-700 dark:text-green-400">User exists</p>
                      <p className="text-sm text-slate-600 dark:text-slate-300 mt-1">
                        ID: {lookupResult.user.user_id} · {lookupResult.user.user_name} · {lookupResult.user.email}
                      </p>
                    </div>
                    <Button
                      type="button"
                      size="sm"
                      onClick={() => openAddWithUser(lookupResult.user!)}
                    >
                      Add to authorization
                    </Button>
                  </div>
                ) : (
                  <p className="text-slate-600 dark:text-slate-400">User not found.</p>
                )}
              </div>
            )}
          </CardContent>
        </Card>

        {/* Checklist table */}
        <Card>
          <CardHeader>
            <CardTitle>Authorizations</CardTitle>
            <CardDescription>Users authorized per business. Revoke to remove access.</CardDescription>
            <div className="pt-2">
              <Label className="text-xs text-slate-500">Filter by business</Label>
              <Select value={filterBusinessId || "all"} onValueChange={(v) => setFilterBusinessId(v === "all" ? "" : v)}>
                <SelectTrigger className="w-[220px] mt-1">
                  <SelectValue placeholder="All businesses" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All businesses</SelectItem>
                  {businesses.map((b) => (
                    <SelectItem key={b.business_id} value={String(b.business_id)}>
                      {b.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </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 authorizations yet. Add one or create businesses first.
              </p>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm">
                  <thead>
                    <tr className="border-b border-slate-200 dark:border-slate-700">
                      <th className="text-left py-3 px-2 font-medium">Business</th>
                      <th className="text-left py-3 px-2 font-medium">User</th>
                      <th className="text-left py-3 px-2 font-medium">Authorized by</th>
                      <th className="text-left py-3 px-2 font-medium">Date</th>
                      <th className="w-[80px] py-3 px-2 font-medium">Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    {list.map((row) => (
                      <tr key={row.id} className="border-b border-slate-100 dark:border-slate-800">
                        <td className="py-3 px-2">{row.business_name ?? row.business_id}</td>
                        <td className="py-3 px-2">
                          {row.user_name ?? row.user_email ?? `User #${row.user_id}`}
                          {row.user_email && (
                            <span className="text-slate-500 dark:text-slate-400 block text-xs">{row.user_email}</span>
                          )}
                        </td>
                        <td className="py-3 px-2">{row.authorized_by_name ?? row.authorized_by_email ?? `Admin #${row.authorized_by_admin_id}`}</td>
                        <td className="py-3 px-2 text-slate-500 dark:text-slate-400">
                          {new Date(row.created_at).toLocaleDateString()}
                        </td>
                        <td className="py-3 px-2">
                          <Button
                            variant="ghost"
                            size="sm"
                            className="text-red-600 dark:text-red-400"
                            onClick={() => handleRevoke(row.id)}
                            disabled={revokeId === row.id}
                          >
                            {revokeId === row.id ? <Loader2 className="h-4 w-4 animate-spin" /> : <Trash2 className="h-4 w-4" />}
                          </Button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Add authorization dialog */}
      <Dialog open={addOpen} onOpenChange={setAddOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Add authorization</DialogTitle>
            <DialogDescription>Choose a business and a user to authorize. Use the lookup above to find a user, or enter user ID if you know it.</DialogDescription>
          </DialogHeader>
          <form onSubmit={handleAddAuthorization}>
            <div className="space-y-4 py-4">
              <div className="space-y-2">
                <Label>Business</Label>
                <Select value={addBusinessId} onValueChange={setAddBusinessId} required>
                  <SelectTrigger>
                    <SelectValue placeholder="Select business" />
                  </SelectTrigger>
                  <SelectContent>
                    {businesses.map((b) => (
                      <SelectItem key={b.business_id} value={String(b.business_id)}>
                        {b.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              {addUserId != null ? (
                <div className="rounded-lg border bg-slate-50 dark:bg-slate-900/50 p-3 text-sm">
                  Authorizing user ID: <strong>{addUserId}</strong>
                  <Button
                    type="button"
                    variant="link"
                    className="ml-2 h-auto p-0 text-xs"
                    onClick={() => setAddUserId(null)}
                  >
                    Change
                  </Button>
                </div>
              ) : (
                <div className="space-y-2">
                  <Label>User ID (or use Look up above and click &quot;Add to authorization&quot;)</Label>
                  <Input
                    type="number"
                    min={1}
                    placeholder="User ID"
                    onChange={(e) => {
                      const v = e.target.value ? parseInt(e.target.value, 10) : null
                      setAddUserId(Number.isNaN(v as number) ? null : v)
                    }}
                  />
                </div>
              )}
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setAddOpen(false)} disabled={addSubmitting}>
                Cancel
              </Button>
              <Button
                type="submit"
                disabled={addSubmitting || !addBusinessId || addUserId == null}
              >
                {addSubmitting ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : null}
                Authorize
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  )
}
