import React, { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@core/components/ui/card'
import { Badge } from '@core/components/ui/badge'
import { Button } from '@core/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@core/components/ui/tabs'
import { useApi } from '@core/hooks/useApi'
import { formatDistanceToNow } from 'date-fns'

interface SignalMetrics {
  total_signals: number
  signals_today: number
  signals_this_week: number
  conversion_rate: number
  top_sources: Array<{ source: string; count: number }>
  recent_signals: Array<{
    id: string
    action_type: string
    source: string
    stage: string
    created_at: string
    account_name?: string
  }>
}

interface FunnelMetrics {
  anonymous_visitors: number
  identified_users: number
  installed_instances: number
  conversion_rates: {
    anonymous_to_identified: number
    identified_to_installed: number
  }
  stage_distribution: Array<{
    stage: string
    count: number
    percentage: number
  }>
}

export default function OperationsDashboard() {
  const [signalMetrics, setSignalMetrics] = useState<SignalMetrics | null>(null)
  const [funnelMetrics, setFunnelMetrics] = useState<FunnelMetrics | null>(null)
  const [loading, setLoading] = useState(true)
  const { apiFetch } = useApi()

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

  const loadMetrics = async () => {
    try {
      const [signals, funnel] = await Promise.all([
        apiFetch('/admin/signals/metrics'),
        apiFetch('/admin/funnel/metrics')
      ])
      setSignalMetrics(signals)
      setFunnelMetrics(funnel)
    } catch (error) {
      console.error('Failed to load metrics:', error)
    } finally {
      setLoading(false)
    }
  }

  if (loading) {
    return <div className="p-6">Loading operations dashboard...</div>
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Operations Dashboard</h1>
          <p className="text-muted-foreground">
            Monitor signal tracking, funnel performance, and system health
          </p>
        </div>
        <Button onClick={loadMetrics}>Refresh</Button>
      </div>

      {/* Key Metrics */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Total Signals</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{signalMetrics?.total_signals || 0}</div>
            <p className="text-xs text-muted-foreground">
              +{signalMetrics?.signals_today || 0} today
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Conversion Rate</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{(signalMetrics?.conversion_rate || 0).toFixed(1)}%</div>
            <p className="text-xs text-muted-foreground">
              Last 30 days
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Active Users</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{funnelMetrics?.identified_users || 0}</div>
            <p className="text-xs text-muted-foreground">
              Identified users
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium">Installations</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{funnelMetrics?.installed_instances || 0}</div>
            <p className="text-xs text-muted-foreground">
              Active instances
            </p>
          </CardContent>
        </Card>
      </div>

      <Tabs defaultValue="signals" className="space-y-4">
        <TabsList>
          <TabsTrigger value="signals">Signal Analytics</TabsTrigger>
          <TabsTrigger value="funnel">Funnel Performance</TabsTrigger>
          <TabsTrigger value="health">System Health</TabsTrigger>
        </TabsList>

        <TabsContent value="signals" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Top Signal Sources</CardTitle>
                <CardDescription>Most active signal sources</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {signalMetrics?.top_sources?.map((source, index) => (
                    <div key={source.source} className="flex justify-between items-center">
                      <div className="flex items-center space-x-2">
                        <Badge variant="outline">{index + 1}</Badge>
                        <span className="capitalize">{source.source}</span>
                      </div>
                      <span className="font-medium">{source.count}</span>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Recent Signals</CardTitle>
                <CardDescription>Latest signal activity</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  {signalMetrics?.recent_signals?.slice(0, 10).map((signal) => (
                    <div key={signal.id} className="flex justify-between items-center text-sm">
                      <div>
                        <span className="font-medium">{signal.action_type}</span>
                        <div className="text-muted-foreground">
                          {signal.account_name || 'Anonymous'} • {signal.source}
                        </div>
                      </div>
                      <div className="text-right">
                        <Badge variant="outline" className="text-xs">
                          {signal.stage}
                        </Badge>
                        <div className="text-xs text-muted-foreground">
                          {formatDistanceToNow(new Date(signal.created_at), { addSuffix: true })}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="funnel" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Funnel Stages</CardTitle>
                <CardDescription>User progression through funnel</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {funnelMetrics?.stage_distribution?.map((stage) => (
                    <div key={stage.stage} className="space-y-1">
                      <div className="flex justify-between text-sm">
                        <span className="capitalize">{stage.stage}</span>
                        <span>{stage.count} ({stage.percentage.toFixed(1)}%)</span>
                      </div>
                      <div className="w-full bg-secondary rounded-full h-2">
                        <div
                          className="bg-primary h-2 rounded-full"
                          style={{ width: `${stage.percentage}%` }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Conversion Rates</CardTitle>
                <CardDescription>Stage-to-stage conversion</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="text-center">
                    <div className="text-2xl font-bold text-green-600">
                      {(funnelMetrics?.conversion_rates.anonymous_to_identified || 0).toFixed(1)}%
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Anonymous → Identified
                    </p>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-blue-600">
                      {(funnelMetrics?.conversion_rates.identified_to_installed || 0).toFixed(1)}%
                    </div>
                    <p className="text-sm text-muted-foreground">
                      Identified → Installed
                    </p>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="health" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>System Health</CardTitle>
              <CardDescription>Overall system status and performance</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div className="text-center">
                  <div className="text-2xl font-bold text-green-600">Healthy</div>
                  <p className="text-sm text-muted-foreground">Signal Processing</p>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-green-600">Operational</div>
                  <p className="text-sm text-muted-foreground">Database</p>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-green-600">Normal</div>
                  <p className="text-sm text-muted-foreground">API Response</p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
