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 { Input } from '@core/components/ui/input'
import { Label } from '@core/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@core/components/ui/select'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@core/components/ui/table'
import { useApi } from '@core/hooks/useApi'
import { formatDistanceToNow } from 'date-fns'
import { Search, Filter, Download } from 'lucide-react'

interface SignalRecord {
  id: string
  action_type: string
  action_value: number
  stage: string
  source: string
  created_at: string
  account_name?: string
  person_email?: string
  anonymous_id?: string
  session_id?: string
  rating: number
  raw_score: number
  referrer_domain?: string
  utm_source?: string
  utm_medium?: string
  utm_campaign?: string
}

interface AuditFilters {
  date_from?: string
  date_to?: string
  source?: string
  stage?: string
  action_type?: string
  min_rating?: number
  account_id?: string
  search?: string
}

export default function AuditFunnelPage() {
  const [signals, setSignals] = useState<SignalRecord[]>([])
  const [loading, setLoading] = useState(false)
  const [filters, setFilters] = useState<AuditFilters>({})
  const [totalCount, setTotalCount] = useState(0)
  const [page, setPage] = useState(1)
  const { apiFetch } = useApi()

  useEffect(() => {
    loadSignals()
  }, [page, filters])

  const loadSignals = async () => {
    setLoading(true)
    try {
      const params = new URLSearchParams({
        page: page.toString(),
        limit: '50',
        ...Object.fromEntries(
          Object.entries(filters).filter(([_, v]) => v != null && v !== '')
        )
      })
      
      const response = await apiFetch(`/admin/signals/audit?${params}`)
      setSignals(response.signals || [])
      setTotalCount(response.total || 0)
    } catch (error) {
      console.error('Failed to load signals:', error)
    } finally {
      setLoading(false)
    }
  }

  const exportData = async () => {
    try {
      const params = new URLSearchParams({
        export: 'true',
        ...Object.fromEntries(
          Object.entries(filters).filter(([_, v]) => v != null && v !== '')
        )
      })
      
      const response = await apiFetch(`/admin/signals/audit?${params}`)
      
      // 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 = `signals-audit-${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)
    }
  }

  const updateFilter = (key: keyof AuditFilters, value: any) => {
    setFilters(prev => ({ ...prev, [key]: value }))
    setPage(1) // Reset to first page when filtering
  }

  const getRatingColor = (rating: number) => {
    if (rating >= 4) return 'bg-green-100 text-green-800'
    if (rating >= 3) return 'bg-yellow-100 text-yellow-800'
    return 'bg-red-100 text-red-800'
  }

  const getSourceColor = (source: string) => {
    const colors = {
      mar: 'bg-blue-100 text-blue-800',
      int: 'bg-purple-100 text-purple-800',
      use: 'bg-green-100 text-green-800',
      manual: 'bg-gray-100 text-gray-800'
    }
    return colors[source as keyof typeof colors] || 'bg-gray-100 text-gray-800'
  }

  return (
    <div className="p-6 space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold">Funnel Audit</h1>
          <p className="text-muted-foreground">
            Detailed audit trail of all funnel signals and conversions
          </p>
        </div>
        <div className="flex space-x-2">
          <Button variant="outline" onClick={exportData}>
            <Download className="w-4 h-4 mr-2" />
            Export
          </Button>
          <Button onClick={loadSignals}>Refresh</Button>
        </div>
      </div>

      {/* Filters */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Filter className="w-4 h-4 mr-2" />
            Filters
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-6 gap-4">
            <div>
              <Label htmlFor="search">Search</Label>
              <div className="relative">
                <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  id="search"
                  placeholder="Email, domain..."
                  className="pl-8"
                  value={filters.search || ''}
                  onChange={(e) => updateFilter('search', e.target.value)}
                />
              </div>
            </div>
            
            <div>
              <Label htmlFor="date_from">From Date</Label>
              <Input
                id="date_from"
                type="date"
                value={filters.date_from || ''}
                onChange={(e) => updateFilter('date_from', e.target.value)}
              />
            </div>
            
            <div>
              <Label htmlFor="date_to">To Date</Label>
              <Input
                id="date_to"
                type="date"
                value={filters.date_to || ''}
                onChange={(e) => updateFilter('date_to', e.target.value)}
              />
            </div>
            
            <div>
              <Label htmlFor="source">Source</Label>
              <Select value={filters.source || ''} onValueChange={(value) => updateFilter('source', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="All sources" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">All sources</SelectItem>
                  <SelectItem value="mar">Marketing</SelectItem>
                  <SelectItem value="int">Internal</SelectItem>
                  <SelectItem value="use">Usage</SelectItem>
                  <SelectItem value="manual">Manual</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div>
              <Label htmlFor="stage">Stage</Label>
              <Select value={filters.stage || ''} onValueChange={(value) => updateFilter('stage', value)}>
                <SelectTrigger>
                  <SelectValue placeholder="All stages" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">All stages</SelectItem>
                  <SelectItem value="anonymous">Anonymous</SelectItem>
                  <SelectItem value="identified">Identified</SelectItem>
                  <SelectItem value="installed">Installed</SelectItem>
                </SelectContent>
              </Select>
            </div>
            
            <div>
              <Label htmlFor="min_rating">Min Rating</Label>
              <Select value={filters.min_rating?.toString() || ''} onValueChange={(value) => updateFilter('min_rating', value ? parseInt(value) : undefined)}>
                <SelectTrigger>
                  <SelectValue placeholder="Any rating" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="">Any rating</SelectItem>
                  <SelectItem value="4">4+ (High)</SelectItem>
                  <SelectItem value="3">3+ (Medium)</SelectItem>
                  <SelectItem value="2">2+ (Low)</SelectItem>
                  <SelectItem value="1">1+ (All)</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Results Summary */}
      <Card>
        <CardHeader>
          <CardTitle>Results</CardTitle>
          <CardDescription>
            Showing {signals.length} of {totalCount} signals
          </CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Timestamp</TableHead>
                <TableHead>Action</TableHead>
                <TableHead>User</TableHead>
                <TableHead>Source</TableHead>
                <TableHead>Stage</TableHead>
                <TableHead>Rating</TableHead>
                <TableHead>Score</TableHead>
                <TableHead>Referrer</TableHead>
                <TableHead>UTM</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-8">
                    Loading signals...
                  </TableCell>
                </TableRow>
              ) : signals.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={9} className="text-center py-8">
                    No signals found matching the current filters
                  </TableCell>
                </TableRow>
              ) : (
                signals.map((signal) => (
                  <TableRow key={signal.id}>
                    <TableCell>
                      <div>
                        <div className="text-sm">
                          {formatDistanceToNow(new Date(signal.created_at), { addSuffix: true })}
                        </div>
                        <div className="text-xs text-muted-foreground">
                          {new Date(signal.created_at).toLocaleString()}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        <div className="font-medium">{signal.action_type}</div>
                        <div className="text-sm text-muted-foreground">
                          Value: {signal.action_value}
                        </div>
                      </div>
                    </TableCell>
                    <TableCell>
                      <div>
                        {signal.account_name ? (
                          <div>
                            <div className="font-medium">{signal.account_name}</div>
                            <div className="text-sm text-muted-foreground">{signal.person_email}</div>
                          </div>
                        ) : signal.anonymous_id ? (
                          <div className="text-sm text-muted-foreground">
                            Anonymous: {signal.anonymous_id.slice(0, 8)}...
                          </div>
                        ) : (
                          <div className="text-sm text-muted-foreground">Unknown</div>
                        )}
                      </div>
                    </TableCell>
                    <TableCell>
                      <Badge className={getSourceColor(signal.source)}>
                        {signal.source}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <Badge variant="outline">{signal.stage}</Badge>
                    </TableCell>
                    <TableCell>
                      <Badge className={getRatingColor(signal.rating)}>
                        {signal.rating}
                      </Badge>
                    </TableCell>
                    <TableCell>
                      <span className="font-mono text-sm">{signal.raw_score}</span>
                    </TableCell>
                    <TableCell>
                      <div className="max-w-32 truncate text-sm">
                        {signal.referrer_domain || 'Direct'}
                      </div>
                    </TableCell>
                    <TableCell>
                      <div className="text-sm space-y-1">
                        {signal.utm_source && (
                          <div>Source: {signal.utm_source}</div>
                        )}
                        {signal.utm_medium && (
                          <div>Medium: {signal.utm_medium}</div>
                        )}
                        {signal.utm_campaign && (
                          <div>Campaign: {signal.utm_campaign}</div>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
          
          {/* Pagination */}
          {totalCount > 50 && (
            <div className="flex justify-between items-center mt-4">
              <div className="text-sm text-muted-foreground">
                Page {page} of {Math.ceil(totalCount / 50)}
              </div>
              <div className="flex space-x-2">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                  disabled={page === 1}
                >
                  Previous
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setPage(p => p + 1)}
                  disabled={page >= Math.ceil(totalCount / 50)}
                >
                  Next
                </Button>
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
