import { useState, useEffect, useCallback } from "react"
import {
  BarChart3,
  ShieldAlert,
  ShieldCheck,
  Globe,
  RefreshCw,
  Loader2,
  AlertTriangle,
  Calendar,
  MapPin,
} from "lucide-react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table"
import { CaptchaAnalyticsSummary, recaptchaLocations } from "../../config"

// Helper to format location IDs to readable names
function formatLocation(locationId: string): string {
  const loc = recaptchaLocations.find((l) => l.id === locationId)
  return loc ? loc.name : locationId
}

// Helper to format dates
function formatDate(dateStr: string): string {
  const d = new Date(dateStr)
  return d.toLocaleDateString(undefined, {
    month: "short",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  })
}

function formatShortDate(dateStr: string): string {
  const d = new Date(dateStr)
  return d.toLocaleDateString(undefined, { month: "short", day: "numeric" })
}

export function AnalyticsTab() {
  const [analytics, setAnalytics] = useState<CaptchaAnalyticsSummary | null>(null)
  const [loading, setLoading] = useState(true)
  const [period, setPeriod] = useState<"7d" | "30d">("30d")

  const loadAnalytics = useCallback(async () => {
    setLoading(true)
    try {
      const apiUrl =
        window.swiftCommerceData?.apiUrl || "/wp-json/swift-commerce/v1"
      const response = await fetch(
        `${apiUrl}/recaptcha/analytics?period=${period}`,
        {
          headers: {
            "X-WP-Nonce": window.swiftCommerceData?.restNonce || "",
          },
        }
      )

      if (response.ok) {
        const result = await response.json()
        if (result.success && result.data) {
          setAnalytics(result.data)
        }
      }
    } catch (error) {
      console.error("Failed to load CAPTCHA analytics:", error)
    } finally {
      setLoading(false)
    }
  }, [period])

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

  if (loading) {
    return (
      <div className="flex items-center justify-center p-12">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    )
  }

  if (!analytics) {
    return (
      <div className="flex flex-col items-center justify-center py-16 text-center">
        <BarChart3 className="h-12 w-12 text-muted-foreground/50 mb-4" />
        <h3 className="text-lg font-medium">No analytics data yet</h3>
        <p className="text-sm text-muted-foreground mt-1">
          Analytics will populate once CAPTCHA verifications start being logged.
        </p>
      </div>
    )
  }

  const filteredDays =
    period === "7d"
      ? analytics.byDay.slice(-7)
      : analytics.byDay

  return (
    <div className="space-y-6">
      {/* Header with controls */}
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-base font-semibold">CAPTCHA Analytics</h3>
          <p className="text-sm text-muted-foreground">
            Monitor verification attempts and blocked threats.
          </p>
        </div>
        <div className="flex items-center gap-3">
          <PeriodSelector period={period} onChange={setPeriod} />
          <Button
            variant="outline"
            size="sm"
            onClick={loadAnalytics}
            className="gap-2"
          >
            <RefreshCw className="h-4 w-4" />
            Refresh
          </Button>
        </div>
      </div>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        <StatCard
          title="Total Checks"
          value={analytics.totalChecks}
          icon={ShieldCheck}
          description="Total CAPTCHA verifications"
        />
        <StatCard
          title="Passed"
          value={analytics.totalPassed}
          icon={ShieldCheck}
          description="Successful verifications"
        />
        <StatCard
          title="Failed"
          value={analytics.totalFailed}
          icon={ShieldAlert}
          description="Blocked attempts"
        />
        <StatCard
          title="Fail Rate"
          value={`${analytics.failRate.toFixed(1)}%`}
          icon={AlertTriangle}
          description="Percentage of failed checks"
        />
      </div>

      {/* Daily Trend */}
      {filteredDays.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Calendar className="h-5 w-5" />
              Daily Trend
            </CardTitle>
            <CardDescription>
              Passed vs failed verifications over time.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {filteredDays.map((day) => {
                const total = day.passed + day.failed
                const passedPct = total > 0 ? (day.passed / total) * 100 : 100
                const failedPct = total > 0 ? (day.failed / total) * 100 : 0
                return (
                  <div key={day.date} className="flex items-center gap-3">
                    <span className="text-xs text-muted-foreground w-16 shrink-0">
                      {formatShortDate(day.date)}
                    </span>
                    <div className="flex-1 flex h-5 rounded-full overflow-hidden bg-muted">
                      {passedPct > 0 && (
                        <div
                          className="bg-green-500 transition-all"
                          style={{ width: `${passedPct}%` }}
                        />
                      )}
                      {failedPct > 0 && (
                        <div
                          className="bg-red-400 transition-all"
                          style={{ width: `${failedPct}%` }}
                        />
                      )}
                    </div>
                    <div className="flex items-center gap-2 text-xs shrink-0 w-24 justify-end">
                      <span className="text-green-600 font-medium">
                        {day.passed}
                      </span>
                      <span className="text-muted-foreground">/</span>
                      <span className="text-red-500 font-medium">
                        {day.failed}
                      </span>
                    </div>
                  </div>
                )
              })}
            </div>
            <div className="flex items-center gap-4 mt-4 text-xs text-muted-foreground">
              <div className="flex items-center gap-1.5">
                <div className="w-3 h-3 rounded-full bg-green-500" />
                Passed
              </div>
              <div className="flex items-center gap-1.5">
                <div className="w-3 h-3 rounded-full bg-red-400" />
                Failed
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* By Location */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <MapPin className="h-5 w-5" />
              By Location
            </CardTitle>
            <CardDescription>
              Verification results per form location.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {Object.keys(analytics.byLocation).length > 0 ? (
              <div className="space-y-3">
                {Object.entries(analytics.byLocation).map(
                  ([locationId, data]) => {
                    const total = data.passed + data.failed
                    const failPct =
                      total > 0 ? (data.failed / total) * 100 : 0
                    return (
                      <div key={locationId} className="space-y-1.5">
                        <div className="flex items-center justify-between text-sm">
                          <span className="font-medium">
                            {formatLocation(locationId)}
                          </span>
                          <span className="text-muted-foreground">
                            {data.passed} passed / {data.failed} failed
                          </span>
                        </div>
                        <div className="w-full bg-muted rounded-full h-2">
                          <div
                            className="bg-red-400 h-2 rounded-full transition-all"
                            style={{
                              width: `${Math.max(failPct, failPct > 0 ? 2 : 0)}%`,
                            }}
                          />
                        </div>
                      </div>
                    )
                  }
                )}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground text-center py-6">
                No location data available yet.
              </p>
            )}
          </CardContent>
        </Card>

        {/* Top Blocked IPs */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <Globe className="h-5 w-5" />
              Top Blocked IPs
            </CardTitle>
            <CardDescription>
              IP addresses with the most failed attempts.
            </CardDescription>
          </CardHeader>
          <CardContent>
            {analytics.topBlockedIPs.length > 0 ? (
              <div className="space-y-2">
                {analytics.topBlockedIPs.map((entry, idx) => (
                  <div
                    key={entry.ip}
                    className="flex items-center justify-between rounded-lg border p-3"
                  >
                    <div className="flex items-center gap-3">
                      <span className="text-sm font-medium text-muted-foreground w-5">
                        {idx + 1}.
                      </span>
                      <code className="text-sm font-mono bg-muted px-2 py-0.5 rounded">
                        {entry.ip}
                      </code>
                    </div>
                    <Badge variant="destructive" className="text-xs">
                      {entry.count} {entry.count === 1 ? "failure" : "failures"}
                    </Badge>
                  </div>
                ))}
              </div>
            ) : (
              <p className="text-sm text-muted-foreground text-center py-6">
                No blocked IPs recorded yet.
              </p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Recent Failures */}
      {analytics.recentFailures.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-base">
              <ShieldAlert className="h-5 w-5" />
              Recent Failed Attempts
            </CardTitle>
            <CardDescription>
              Latest CAPTCHA verification failures.
            </CardDescription>
          </CardHeader>
          <CardContent>
            <div className="border rounded-lg overflow-hidden">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="pl-4">Time</TableHead>
                    <TableHead>Location</TableHead>
                    <TableHead>IP Address</TableHead>
                    <TableHead>Provider</TableHead>
                    <TableHead className="pr-4">Reason</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {analytics.recentFailures.map((entry) => (
                    <TableRow key={entry.id}>
                      <TableCell className="pl-4 text-xs text-muted-foreground">
                        {formatDate(entry.created_at)}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="text-xs">
                          {formatLocation(entry.location)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <code className="text-xs font-mono bg-muted px-1.5 py-0.5 rounded">
                          {entry.ip_address}
                        </code>
                      </TableCell>
                      <TableCell className="text-xs">
                        {entry.provider || "google-recaptcha"}
                      </TableCell>
                      <TableCell className="pr-4 text-xs text-muted-foreground max-w-[200px] truncate">
                        {entry.fail_reason || "Verification failed"}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}

// --- Sub-components ---

function StatCard({
  title,
  value,
  icon: Icon,
  description,
}: {
  title: string
  value: string | number
  icon: React.ComponentType<{ className?: string }>
  description: string
}) {
  return (
    <Card>
      <CardHeader className="flex flex-row items-center justify-between pb-2">
        <CardTitle className="text-sm font-medium text-muted-foreground">
          {title}
        </CardTitle>
        <Icon className="h-4 w-4 text-muted-foreground" />
      </CardHeader>
      <CardContent>
        <div className="text-2xl font-bold">{value}</div>
        <p className="text-xs text-muted-foreground mt-1">{description}</p>
      </CardContent>
    </Card>
  )
}

function PeriodSelector({
  period,
  onChange,
}: {
  period: "7d" | "30d"
  onChange: (p: "7d" | "30d") => void
}) {
  return (
    <div className="flex items-center rounded-md border p-0.5">
      <button
        onClick={() => onChange("7d")}
        className={`px-3 py-1 text-xs font-medium rounded transition-colors ${
          period === "7d"
            ? "bg-foreground text-background"
            : "text-muted-foreground hover:text-foreground"
        }`}
      >
        7 days
      </button>
      <button
        onClick={() => onChange("30d")}
        className={`px-3 py-1 text-xs font-medium rounded transition-colors ${
          period === "30d"
            ? "bg-foreground text-background"
            : "text-muted-foreground hover:text-foreground"
        }`}
      >
        30 days
      </button>
    </div>
  )
}
