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 { Progress } from '@core/components/ui/progress'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@core/components/ui/tabs'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@core/components/ui/table'
import { useApi } from '@core/hooks/useApi'
import { formatDistanceToNow } from 'date-fns'
import { Download, TrendingUp, Users, Package } from 'lucide-react'

interface InstallMetrics {
  total_downloads: number
  unique_installers: number
  active_instances: number
  conversion_funnel: {
    downloads: number
    installations: number
    first_use: number
    claimed: number
  }
  install_trends: Array<{
    date: string
    downloads: number
    installations: number
  }>
  recent_installs: Array<{
    id: string
    serial: string
    app_version: string
    environment: string
    first_seen_at: string
    last_signal_at: string
    claimed_by?: string
    claimed_at?: string
    account_name?: string
  }>
  top_versions: Array<{
    version: string
    count: number
    percentage: number
  }>
}

export default function InstallFunnelPage() {
  const [metrics, setMetrics] = useState<InstallMetrics | null>(null)
  const [loading, setLoading] = useState(true)
  const { apiFetch } = useApi()

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

  const loadMetrics = async () => {
    try {
      const data = await apiFetch('/admin/install-funnel/metrics')
      setMetrics(data)
    } catch (error) {
      console.error('Failed to load install metrics:', error)
    } finally {
      setLoading(false)
    }
  }

  const exportData = async () => {
    try {
      const response = await apiFetch('/admin/install-funnel/exportData')
      
      // Create download link
      const blob = new Blob([JSON.stringify(response, null, 2)], { type: 'application/json' })
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `install-funnel-${new Date().toISOString().split('T')[0]}.json`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
    } catch (error) {
      console.error('Failed to export data:', error)
    }
  }

  if (loading) {
    return <div className="p-6">Loading install funnel data...</div>
  }

  const conversionRates = metrics ? {
    download_to_install: (metrics.conversion_funnel.installations / metrics.conversion_funnel.downloads * 100) || 0,
    install_to_use: (metrics.conversion_funnel.first_use / metrics.conversion_funnel.installations * 100) || 0,
    use_to_claim: (metrics.conversion_funnel.claimed / metrics.conversion_funnel.first_use * 100) || 0
  } : { download_to_install: 0, install_to_use: 0, use_to_claim: 0 }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Install Funnel</h1>
          <p className="text-muted-foreground">
            Track downloads, installations, and adoption metrics
          </p>
        </div>
        <div className="flex space-x-2">
          <Button variant="outline" onClick={exportData}>
            <Download className="w-4 h-4 mr-2" />
            Export Data
          </Button>
          <Button onClick={loadMetrics}>Refresh</Button>
        </div>
      </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 flex items-center">
              <Download className="w-4 h-4 mr-2" />
              Total Downloads
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{metrics?.total_downloads || 0}</div>
            <p className="text-xs text-muted-foreground">
              All-time downloads
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium flex items-center">
              <Users className="w-4 h-4 mr-2" />
              Unique Installers
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{metrics?.unique_installers || 0}</div>
            <p className="text-xs text-muted-foreground">
              Distinct installations
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium flex items-center">
              <Package className="w-4 h-4 mr-2" />
              Active Instances
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{metrics?.active_instances || 0}</div>
            <p className="text-xs text-muted-foreground">
              Used in last 7 days
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="text-sm font-medium flex items-center">
              <TrendingUp className="w-4 h-4 mr-2" />
              Overall Conversion
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {conversionRates.download_to_install.toFixed(1)}%
            </div>
            <p className="text-xs text-muted-foreground">
              Download → Install
            </p>
          </CardContent>
        </Card>
      </div>

      <Tabs defaultValue="funnel" className="space-y-4">
        <TabsList>
          <TabsTrigger value="funnel">Conversion Funnel</TabsTrigger>
          <TabsTrigger value="instances">Instance Details</TabsTrigger>
          <TabsTrigger value="trends">Installation Trends</TabsTrigger>
          <TabsTrigger value="versions">Version Analytics</TabsTrigger>
        </TabsList>

        <TabsContent value="funnel" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>Conversion Funnel</CardTitle>
                <CardDescription>User progression from download to claim</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {metrics?.conversion_funnel && (
                    <>
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span>Downloads</span>
                          <span className="font-medium">{metrics.conversion_funnel.downloads}</span>
                        </div>
                        <Progress value={100} className="h-2" />
                      </div>
                      
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span>Installations</span>
                          <span className="font-medium">{metrics.conversion_funnel.installations}</span>
                        </div>
                        <Progress value={conversionRates.download_to_install} className="h-2" />
                        <p className="text-xs text-muted-foreground">
                          {conversionRates.download_to_install.toFixed(1)}% conversion
                        </p>
                      </div>
                      
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span>First Use</span>
                          <span className="font-medium">{metrics.conversion_funnel.first_use}</span>
                        </div>
                        <Progress value={conversionRates.install_to_use} className="h-2" />
                        <p className="text-xs text-muted-foreground">
                          {conversionRates.install_to_use.toFixed(1)}% conversion
                        </p>
                      </div>
                      
                      <div className="space-y-2">
                        <div className="flex justify-between">
                          <span>Claimed</span>
                          <span className="font-medium">{metrics.conversion_funnel.claimed}</span>
                        </div>
                        <Progress value={conversionRates.use_to_claim} className="h-2" />
                        <p className="text-xs text-muted-foreground">
                          {conversionRates.use_to_claim.toFixed(1)}% conversion
                        </p>
                      </div>
                    </>
                  )}
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Conversion Insights</CardTitle>
                <CardDescription>Key metrics and drop-off points</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex justify-between items-center p-3 bg-blue-50 rounded-lg">
                    <div>
                      <div className="font-medium">Download to Install</div>
                      <div className="text-sm text-muted-foreground">
                        {conversionRates.download_to_install.toFixed(1)}% conversion
                      </div>
                    </div>
                    <Badge variant={conversionRates.download_to_install > 50 ? 'default' : 'destructive'}>
                      {conversionRates.download_to_install > 50 ? 'Good' : 'Needs Attention'}
                    </Badge>
                  </div>
                  
                  <div className="flex justify-between items-center p-3 bg-green-50 rounded-lg">
                    <div>
                      <div className="font-medium">Install to Use</div>
                      <div className="text-sm text-muted-foreground">
                        {conversionRates.install_to_use.toFixed(1)}% conversion
                      </div>
                    </div>
                    <Badge variant={conversionRates.install_to_use > 70 ? 'default' : 'destructive'}>
                      {conversionRates.install_to_use > 70 ? 'Good' : 'Needs Attention'}
                    </Badge>
                  </div>
                  
                  <div className="flex justify-between items-center p-3 bg-purple-50 rounded-lg">
                    <div>
                      <div className="font-medium">Use to Claim</div>
                      <div className="text-sm text-muted-foreground">
                        {conversionRates.use_to_claim.toFixed(1)}% conversion
                      </div>
                    </div>
                    <Badge variant={conversionRates.use_to_claim > 30 ? 'default' : 'destructive'}>
                      {conversionRates.use_to_claim > 30 ? 'Good' : 'Needs Attention'}
                    </Badge>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="instances" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Recent Installations</CardTitle>
              <CardDescription>Latest instance installations and their status</CardDescription>
            </CardHeader>
            <CardContent>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Instance ID</TableHead>
                    <TableHead>Version</TableHead>
                    <TableHead>Environment</TableHead>
                    <TableHead>First Seen</TableHead>
                    <TableHead>Last Activity</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead>Owner</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {metrics?.recent_installs?.map((instance) => (
                    <TableRow key={instance.id}>
                      <TableCell>
                        <code className="text-xs bg-muted px-1 py-0.5 rounded">
                          {instance.serial.slice(0, 12)}...
                        </code>
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{instance.app_version}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge 
                          variant={instance.environment === 'production' ? 'default' : 'secondary'}
                        >
                          {instance.environment}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          {formatDistanceToNow(new Date(instance.first_seen_at), { addSuffix: true })}
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="text-sm">
                          {formatDistanceToNow(new Date(instance.last_signal_at), { addSuffix: true })}
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={instance.claimed_by ? 'default' : 'secondary'}>
                          {instance.claimed_by ? 'Claimed' : 'Unclaimed'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        {instance.account_name ? (
                          <div>
                            <div className="font-medium text-sm">{instance.account_name}</div>
                            <div className="text-xs text-muted-foreground">{instance.claimed_by}</div>
                          </div>
                        ) : (
                          <span className="text-sm text-muted-foreground">Unclaimed</span>
                        )}
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="trends" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Installation Trends</CardTitle>
              <CardDescription>Daily download and installation activity</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-center py-8 text-muted-foreground">
                <TrendingUp className="w-12 h-12 mx-auto mb-4 opacity-50" />
                <p>Chart visualization would be implemented here</p>
                <p className="text-sm">Showing {metrics?.install_trends?.length || 0} days of data</p>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="versions" className="space-y-4">
          <Card>
            <CardHeader>
              <CardTitle>Version Distribution</CardTitle>
              <CardDescription>Active instances by version</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {metrics?.top_versions?.map((version) => (
                  <div key={version.version} className="space-y-1">
                    <div className="flex justify-between items-center">
                      <div className="flex items-center space-x-2">
                        <Badge variant="outline">{version.version}</Badge>
                        <span className="text-sm text-muted-foreground">
                          {version.count} instances
                        </span>
                      </div>
                      <span className="font-medium">{version.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: `${version.percentage}%` }}
                      />
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}
