"use client";

import { useState, useMemo, useEffect, useCallback } from "react";
import { useSettings } from "@/app/lib/settings";
import { runSql, ApiError } from "@/app/lib/api";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Input } from "./ui/input";
import { ScrollArea } from "./ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";
import {
  Users,
  RefreshCw,
  Loader2,
  AlertCircle,
  Search,
  Plus,
  Shield,
  Mail,
  Link2,
  Settings,
} from "lucide-react";
import { toast } from "sonner";

type AuthUser = {
  id: string;
  email?: string;
  display_name?: string;
  provider?: string;
  provider_type?: string;
  created_at?: string;
  last_sign_in_at?: string;
};

type Props = {
  clientName: string | null;
};

export default function AuthPage({ clientName }: Props) {
  const { baseUrl, apiKey } = useSettings();
  const ctx = useMemo(() => ({ baseUrl, apiKey }), [baseUrl, apiKey]);
  const [users, setUsers] = useState<AuthUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [search, setSearch] = useState("");

  const loadUsers = useCallback(async () => {
    if (!clientName) return;
    setLoading(true);
    setError(null);
    try {
      const result = await runSql<AuthUser[]>(
        ctx,
        `SELECT id::text, email, raw_user_meta_data->>'display_name' as display_name, 'email' as provider, 'email' as provider_type, created_at::text, last_sign_in_at::text FROM auth.users ORDER BY created_at DESC LIMIT 100;`,
        { clientName },
      );
      setUsers(result ?? []);
    } catch (err) {
      const msg =
        err instanceof ApiError ? err.message : "Failed to load users";
      setError(msg);
    } finally {
      setLoading(false);
    }
  }, [ctx, clientName]);

  useEffect(() => {
    loadUsers();
  }, [loadUsers]);

  const filtered = useMemo(() => {
    if (!search.trim()) return users;
    const q = search.toLowerCase();
    return users.filter(
      (u) =>
        (u.email ?? "").toLowerCase().includes(q) ||
        (u.display_name ?? "").toLowerCase().includes(q) ||
        u.id.toLowerCase().includes(q),
    );
  }, [users, search]);

  return (
    <div className="flex flex-1 flex-col min-h-0">
      <div className="flex items-center gap-3 border-b border-border px-6 py-3">
        <Users className="h-4 w-4 text-primary" />
        <h2 className="text-sm font-semibold text-foreground">
          Authentication
        </h2>
        <Badge variant="secondary" className="text-caption">
          {users.length} users
        </Badge>
        <div className="flex-1" />
        <Button
          variant="outline"
          size="sm"
          onClick={loadUsers}
          disabled={loading}
        >
          {loading ? (
            <Loader2 className="h-3 w-3 animate-spin" />
          ) : (
            <RefreshCw className="h-3 w-3" />
          )}
        </Button>
        <Button size="sm" disabled>
          <Plus className="h-3 w-3" /> Add user
        </Button>
      </div>

      <Tabs defaultValue="users" className="flex flex-col flex-1 min-h-0">
        <div className="border-b border-border px-6">
          <TabsList className="h-9">
            <TabsTrigger value="users">
              <Users className="h-3 w-3 mr-1" />
              Users
            </TabsTrigger>
            <TabsTrigger value="providers">
              <Shield className="h-3 w-3 mr-1" />
              Providers
            </TabsTrigger>
            <TabsTrigger value="emails">
              <Mail className="h-3 w-3 mr-1" />
              Email
            </TabsTrigger>
            <TabsTrigger value="urls">
              <Link2 className="h-3 w-3 mr-1" />
              URL Config
            </TabsTrigger>
            <TabsTrigger value="settings">
              <Settings className="h-3 w-3 mr-1" />
              Settings
            </TabsTrigger>
          </TabsList>
        </div>

        <TabsContent value="users" className="flex-1 min-h-0 m-0">
          <div className="border-b border-border px-6 py-2">
            <div className="relative max-w-xs">
              <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" />
              <Input
                placeholder="Search by email..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="h-7 pl-7 text-xs"
              />
            </div>
          </div>

          {error && (
            <div className="flex items-center gap-2 border-b border-destructive-border bg-destructive-subtle px-6 py-3 text-xs text-destructive">
              <AlertCircle className="h-3.5 w-3.5" />
              {error}
            </div>
          )}

          {loading && users.length === 0 && (
            <div className="flex flex-1 items-center justify-center py-12">
              <Loader2 className="h-6 w-6 animate-spin text-primary" />
            </div>
          )}

          {!loading && users.length === 0 && !error && (
            <div className="flex flex-1 flex-col items-center justify-center py-12 gap-3 text-muted-foreground">
              <Users className="h-10 w-10 opacity-20" />
              <p className="text-sm">No auth users found</p>
              <p className="text-xs text-muted-foreground-subtle">
                Requires auth.users table (better-auth or Supabase auth)
              </p>
            </div>
          )}

          {filtered.length > 0 && (
            <div className="flex-1 overflow-auto">
              <table className="w-full text-xs">
                <thead className="sticky top-0 z-[5]">
                  <tr className="border-b border-border bg-grid-header">
                    <th className="px-4 py-2 text-left text-caption font-medium text-muted-foreground">
                      UID
                    </th>
                    <th className="px-4 py-2 text-left text-caption font-medium text-muted-foreground">
                      Display name
                    </th>
                    <th className="px-4 py-2 text-left text-caption font-medium text-muted-foreground">
                      Email
                    </th>
                    <th className="px-4 py-2 text-left text-caption font-medium text-muted-foreground">
                      Provider
                    </th>
                    <th className="px-4 py-2 text-left text-caption font-medium text-muted-foreground">
                      Created at
                    </th>
                    <th className="px-4 py-2 text-left text-caption font-medium text-muted-foreground">
                      Last sign in
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border-muted">
                  {filtered.map((user) => (
                    <tr
                      key={user.id}
                      className="hover:bg-accent-muted transition-colors"
                    >
                      <td className="px-4 py-2 font-mono text-caption text-muted-foreground max-w-[120px] truncate">
                        {user.id}
                      </td>
                      <td className="px-4 py-2 text-xs text-foreground">
                        {user.display_name ?? "—"}
                      </td>
                      <td className="px-4 py-2 text-xs text-foreground">
                        {user.email ?? "—"}
                      </td>
                      <td className="px-4 py-2">
                        <Badge variant="secondary" className="text-tiny">
                          {user.provider_type ?? "email"}
                        </Badge>
                      </td>
                      <td className="px-4 py-2 text-caption text-muted-foreground">
                        {user.created_at
                          ? new Date(user.created_at).toLocaleDateString()
                          : "—"}
                      </td>
                      <td className="px-4 py-2 text-caption text-muted-foreground">
                        {user.last_sign_in_at
                          ? new Date(user.last_sign_in_at).toLocaleDateString()
                          : "—"}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </TabsContent>

        <TabsContent value="providers" className="flex-1 m-0">
          <div className="flex flex-1 flex-col items-center justify-center py-16 text-muted-foreground">
            <Shield className="h-10 w-10 opacity-20 mb-3" />
            <p className="text-sm">Auth provider configuration</p>
            <p className="text-xs text-muted-foreground-subtle mt-1">
              Configure OAuth, SAML, and other sign-in providers
            </p>
          </div>
        </TabsContent>

        <TabsContent value="emails" className="flex-1 m-0">
          <div className="flex flex-1 flex-col items-center justify-center py-16 text-muted-foreground">
            <Mail className="h-10 w-10 opacity-20 mb-3" />
            <p className="text-sm">Email templates</p>
            <p className="text-xs text-muted-foreground-subtle mt-1">
              Configure email verification and password reset templates
            </p>
          </div>
        </TabsContent>

        <TabsContent value="urls" className="flex-1 m-0">
          <div className="mx-auto max-w-2xl p-6 space-y-6">
            <section className="rounded border border-border bg-card">
              <div className="border-b border-border px-5 py-4">
                <h3 className="text-sm font-semibold">Site URL</h3>
                <p className="text-xs text-muted-foreground mt-1">
                  Configure the default redirect URL used when a redirect URL is
                  not specified or doesn&apos;t match one from the allow list.
                </p>
              </div>
              <div className="p-5">
                <Input
                  defaultValue="http://localhost:3000"
                  className="font-mono text-xs"
                />
                <Button size="sm" className="mt-3">
                  Save changes
                </Button>
              </div>
            </section>

            <section className="rounded border border-border bg-card">
              <div className="border-b border-border px-5 py-4">
                <div className="flex items-center justify-between">
                  <div>
                    <h3 className="text-sm font-semibold">Redirect URLs</h3>
                    <p className="text-xs text-muted-foreground mt-1">
                      URLs that auth providers are permitted to redirect to post
                      authentication.
                    </p>
                  </div>
                  <Button size="sm">
                    <Plus className="h-3 w-3" /> Add URL
                  </Button>
                </div>
              </div>
              <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                <Link2 className="h-8 w-8 opacity-20 mb-2" />
                <p className="text-xs font-medium text-primary">
                  No Redirect URLs
                </p>
                <p className="text-caption text-muted-foreground-subtle">
                  Auth providers may need a URL to redirect back to
                </p>
              </div>
            </section>
          </div>
        </TabsContent>

        <TabsContent value="settings" className="flex-1 m-0">
          <div className="flex flex-1 flex-col items-center justify-center py-16 text-muted-foreground">
            <Settings className="h-10 w-10 opacity-20 mb-3" />
            <p className="text-sm">General auth settings</p>
            <p className="text-xs text-muted-foreground-subtle mt-1">
              JWT secrets, token expiry, session management
            </p>
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
