"use client"

import { useState, useCallback } from "react"
import {
  Card,
  CardHeader,
  CardTitle,
  CardDescription,
  CardContent,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Progress } from "@/components/ui/progress"
import { Badge } from "@/components/ui/badge"
import {
  Table,
  TableHeader,
  TableBody,
  TableHead,
  TableRow,
  TableCell,
} from "@/components/ui/table"
import {
  Tooltip,
  TooltipTrigger,
  TooltipContent,
} from "@/components/ui/tooltip"
import { Separator } from "@/components/ui/separator"
import {
  Plus,
  Copy,
  Trash2,
  Eye,
  EyeOff,
  Zap,
  Webhook,
  Check,
} from "lucide-react"

const initialKeys = [
  {
    id: "1",
    name: "Production",
    key: "otr_live_a3f8k29d...x7m1",
    fullKey: "otr_live_a3f8k29d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9tx7m1",
    created: "Jan 14, 2026",
    lastUsed: "2 hours ago",
    status: "active" as const,
  },
  {
    id: "2",
    name: "Staging",
    key: "otr_test_b7c2m41n...p9q3",
    fullKey: "otr_test_b7c2m41n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0dp9q3",
    created: "Feb 3, 2026",
    lastUsed: "5 days ago",
    status: "active" as const,
  },
  {
    id: "3",
    name: "CI/CD Pipeline",
    key: "otr_test_x9y1z83a...k4l6",
    fullKey: "otr_test_x9y1z83a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7qk4l6",
    created: "Feb 10, 2026",
    lastUsed: "12 hours ago",
    status: "active" as const,
  },
]

const WEBHOOK_SNIPPET = `curl -X POST https://api.officetranslator.com/v1/translate \\
  -H "Authorization: Bearer otr_live_a3f8..." \\
  -H "Content-Type: multipart/form-data" \\
  -F "file=@report.xlsx" \\
  -F "source=en" \\
  -F "target=fr" \\
  -F "callback_url=https://your-app.com/webhook/done"`

export function ApiAutomationCard() {
  const [keys, setKeys] = useState(initialKeys)
  const [revealedKeys, setRevealedKeys] = useState<Set<string>>(new Set())
  const [copiedId, setCopiedId] = useState<string | null>(null)
  const [copiedSnippet, setCopiedSnippet] = useState(false)

  const usedCalls = 150
  const totalCalls = 500
  const percentUsed = (usedCalls / totalCalls) * 100

  const toggleReveal = useCallback((id: string) => {
    setRevealedKeys((prev) => {
      const next = new Set(prev)
      if (next.has(id)) {
        next.delete(id)
      } else {
        next.add(id)
      }
      return next
    })
  }, [])

  const copyKey = useCallback((id: string, fullKey: string) => {
    navigator.clipboard.writeText(fullKey)
    setCopiedId(id)
    setTimeout(() => setCopiedId(null), 2000)
  }, [])

  const copySnippet = useCallback(() => {
    navigator.clipboard.writeText(WEBHOOK_SNIPPET)
    setCopiedSnippet(true)
    setTimeout(() => setCopiedSnippet(false), 2000)
  }, [])

  const revokeKey = useCallback((id: string) => {
    setKeys((prev) => prev.filter((k) => k.id !== id))
  }, [])

  const generateKey = useCallback(() => {
    const newKey = {
      id: String(Date.now()),
      name: `Key ${keys.length + 1}`,
      key: "otr_live_new_key...xxxx",
      fullKey: "otr_live_new_key_generated_" + Date.now(),
      created: "Just now",
      lastUsed: "Never",
      status: "active" as const,
    }
    setKeys((prev) => [...prev, newKey])
  }, [keys.length])

  return (
    <Card>
      <CardHeader>
        <div className="flex items-center gap-2">
          <div className="flex size-8 items-center justify-center rounded-lg bg-accent/10">
            <Zap className="size-4 text-accent" />
          </div>
          <div>
            <CardTitle className="text-base">API & Automation</CardTitle>
            <CardDescription>Manage your API keys, monitor usage, and configure webhooks</CardDescription>
          </div>
        </div>
      </CardHeader>

      <CardContent className="flex flex-col gap-6">
        {/* Quota Section */}
        <div className="rounded-lg border border-border bg-secondary/30 p-4">
          <div className="flex items-center justify-between">
            <div className="flex flex-col gap-1">
              <span className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
                Monthly Quota
              </span>
              <span className="text-2xl font-semibold tabular-nums text-foreground">
                {usedCalls}
                <span className="text-base font-normal text-muted-foreground">
                  {" / "}{totalCalls} API calls
                </span>
              </span>
            </div>
            <Badge
              variant="secondary"
              className="border border-accent/20 bg-accent/10 text-accent"
            >
              {Math.round(percentUsed)}% used
            </Badge>
          </div>
          <Progress value={percentUsed} className="mt-3 h-1.5 bg-muted" />
          <p className="mt-2 text-xs text-muted-foreground">
            Resets on March 1, 2026. Need more?{" "}
            <button className="font-medium text-accent underline-offset-2 hover:underline">
              Upgrade plan
            </button>
          </p>
        </div>

        {/* API Keys Table */}
        <div>
          <div className="mb-3 flex items-center justify-between">
            <h3 className="text-sm font-semibold text-foreground">Active API Keys</h3>
            <Button size="sm" onClick={generateKey} className="gap-1.5">
              <Plus className="size-3.5" />
              Generate New Key
            </Button>
          </div>
          <div className="rounded-lg border border-border">
            <Table>
              <TableHeader>
                <TableRow className="hover:bg-transparent">
                  <TableHead className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
                    Name
                  </TableHead>
                  <TableHead className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
                    Key
                  </TableHead>
                  <TableHead className="hidden text-xs font-medium uppercase tracking-wider text-muted-foreground md:table-cell">
                    Created
                  </TableHead>
                  <TableHead className="hidden text-xs font-medium uppercase tracking-wider text-muted-foreground lg:table-cell">
                    Last Used
                  </TableHead>
                  <TableHead className="text-right text-xs font-medium uppercase tracking-wider text-muted-foreground">
                    Actions
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {keys.map((apiKey) => (
                  <TableRow key={apiKey.id}>
                    <TableCell className="font-medium text-foreground">
                      {apiKey.name}
                    </TableCell>
                    <TableCell>
                      <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-foreground">
                        {revealedKeys.has(apiKey.id)
                          ? apiKey.fullKey.substring(0, 32) + "..."
                          : apiKey.key}
                      </code>
                    </TableCell>
                    <TableCell className="hidden text-muted-foreground md:table-cell">
                      {apiKey.created}
                    </TableCell>
                    <TableCell className="hidden text-muted-foreground lg:table-cell">
                      {apiKey.lastUsed}
                    </TableCell>
                    <TableCell>
                      <div className="flex items-center justify-end gap-1">
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              onClick={() => toggleReveal(apiKey.id)}
                              aria-label={revealedKeys.has(apiKey.id) ? "Hide key" : "Reveal key"}
                            >
                              {revealedKeys.has(apiKey.id) ? (
                                <EyeOff className="size-3.5 text-muted-foreground" />
                              ) : (
                                <Eye className="size-3.5 text-muted-foreground" />
                              )}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            {revealedKeys.has(apiKey.id) ? "Hide" : "Reveal"}
                          </TooltipContent>
                        </Tooltip>

                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              onClick={() => copyKey(apiKey.id, apiKey.fullKey)}
                              aria-label="Copy key"
                            >
                              {copiedId === apiKey.id ? (
                                <Check className="size-3.5 text-accent" />
                              ) : (
                                <Copy className="size-3.5 text-muted-foreground" />
                              )}
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>
                            {copiedId === apiKey.id ? "Copied!" : "Copy"}
                          </TooltipContent>
                        </Tooltip>

                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              variant="ghost"
                              size="icon-sm"
                              onClick={() => revokeKey(apiKey.id)}
                              aria-label="Revoke key"
                            >
                              <Trash2 className="size-3.5 text-muted-foreground hover:text-destructive" />
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>Revoke</TooltipContent>
                        </Tooltip>
                      </div>
                    </TableCell>
                  </TableRow>
                ))}
                {keys.length === 0 && (
                  <TableRow>
                    <TableCell colSpan={5} className="py-8 text-center text-muted-foreground">
                      No active API keys. Generate one to get started.
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </div>

        <Separator />

        {/* Webhook Code Snippet */}
        <div>
          <div className="mb-3 flex items-center gap-2">
            <Webhook className="size-4 text-accent" />
            <h3 className="text-sm font-semibold text-foreground">Webhook Integration</h3>
          </div>
          <p className="mb-3 text-sm text-muted-foreground">
            Pass a <code className="rounded bg-muted px-1.5 py-0.5 font-mono text-xs text-foreground">callback_url</code> parameter to receive a POST request when your translation is complete.
          </p>
          <div className="relative rounded-lg border border-border bg-foreground p-4">
            <Button
              variant="ghost"
              size="icon-sm"
              className="absolute right-2 top-2 text-background/60 hover:bg-background/10 hover:text-background"
              onClick={copySnippet}
              aria-label="Copy code snippet"
            >
              {copiedSnippet ? (
                <Check className="size-3.5" />
              ) : (
                <Copy className="size-3.5" />
              )}
            </Button>
            <pre className="overflow-x-auto pr-8 text-xs leading-relaxed text-background/90">
              <code>{WEBHOOK_SNIPPET}</code>
            </pre>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}
