'use client'

import { useEffect, useMemo, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useMutation, useQuery } from 'convex/react'
import { api } from '@/convex/_generated/api'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Checkbox } from '@/components/ui/checkbox'
import { Slider } from '@/components/ui/slider'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
import { 
  Dialog, 
  DialogContent, 
  DialogDescription, 
  DialogHeader, 
  DialogTitle,
  DialogFooter
} from '@/components/ui/dialog'
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from '@/components/ui/table'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { 
  Search, 
  Loader2, 
  ExternalLink, 
  MessageSquare, 
  Twitter,
  Users,
  HelpCircle,
  Filter,
  ChevronDown,
  ChevronUp,
  Target,
  Zap,
  AlertCircle,
  BarChart3,
  CheckCircle2,
  Eye,
  Copy
} from 'lucide-react'
import { useProject } from '@/components/project-context'
import type { 
  EnhancedProductAnalysis, 
  Opportunity, 
  PlatformConfig, 
  SearchStrategy 
} from '@/lib/types'

const STRATEGY_INFO: Record<SearchStrategy, { name: string; description: string }> = {
  'direct-keywords': { name: 'Direct Keywords', description: 'People looking for your product category' },
  'problem-pain': { name: 'Problem/Pain', description: 'People experiencing problems you solve' },
  'competitor-alternative': { name: 'Competitor Alternatives', description: 'People switching from competitors' },
  'how-to': { name: 'How-To/Tutorials', description: 'People learning about solutions' },
  'emotional-frustrated': { name: 'Frustration Posts', description: 'Emotional posts about pain points' },
  'comparison': { name: 'Comparisons', description: '"X vs Y" comparison posts' },
  'recommendation': { name: 'Recommendations', description: '"What do you use" requests' }
}

export default function OpportunitiesPage() {
  const router = useRouter()
  const { selectedProjectId } = useProject()
  const upsertOpportunities = useMutation(api.opportunities.upsertBatch)
  const updateOpportunity = useMutation(api.opportunities.updateStatus)
  const [analysis, setAnalysis] = useState<EnhancedProductAnalysis | null>(null)
  const [platforms, setPlatforms] = useState<PlatformConfig[]>([])
  const [strategies, setStrategies] = useState<SearchStrategy[]>([
    'direct-keywords',
    'problem-pain',
    'competitor-alternative'
  ])
  const [intensity, setIntensity] = useState<'broad' | 'balanced' | 'targeted'>('balanced')
  const [isSearching, setIsSearching] = useState(false)
  const [opportunities, setOpportunities] = useState<Opportunity[]>([])
  const [generatedQueries, setGeneratedQueries] = useState<any[]>([])
  const [showQueries, setShowQueries] = useState(false)
  const [selectedOpportunity, setSelectedOpportunity] = useState<Opportunity | null>(null)
  const [replyText, setReplyText] = useState('')
  const [stats, setStats] = useState<any>(null)
  const [searchError, setSearchError] = useState('')
  const [missingSources, setMissingSources] = useState<any[]>([])
  const [statusFilter, setStatusFilter] = useState('all')
  const [intentFilter, setIntentFilter] = useState('all')
  const [minScore, setMinScore] = useState(0)
  const [limit, setLimit] = useState(50)
  const [statusInput, setStatusInput] = useState('new')
  const [notesInput, setNotesInput] = useState('')
  const [tagsInput, setTagsInput] = useState('')

  const projects = useQuery(api.projects.getProjects)
  const latestAnalysis = useQuery(
    api.analyses.getLatestByProject,
    selectedProjectId ? { projectId: selectedProjectId as any } : 'skip'
  )

  const savedOpportunities = useQuery(
    api.opportunities.listByProject,
    selectedProjectId
      ? {
          projectId: selectedProjectId as any,
          status: statusFilter === 'all' ? undefined : statusFilter,
          intent: intentFilter === 'all' ? undefined : intentFilter,
          minScore: minScore > 0 ? minScore / 100 : undefined,
          limit,
        }
      : 'skip'
  )

  const displayOpportunities = useMemo(() => {
    if (!savedOpportunities || savedOpportunities.length === 0) return opportunities
    return savedOpportunities.map((opp: any) => ({
      id: opp._id,
      title: opp.title,
      url: opp.url,
      snippet: opp.snippet,
      platform: opp.platform,
      source: opp.platform,
      relevanceScore: opp.relevanceScore,
      emotionalIntensity: 'low',
      intent: opp.intent,
      matchedKeywords: opp.matchedKeywords,
      matchedProblems: opp.matchedProblems,
      suggestedApproach: opp.suggestedApproach,
      softPitch: opp.softPitch,
      status: opp.status,
      notes: opp.notes,
      tags: opp.tags,
    })) as Opportunity[]
  }, [savedOpportunities, opportunities])

  const selectedSources = useQuery(
    api.dataSources.getProjectDataSources,
    selectedProjectId ? { projectId: selectedProjectId as any } : "skip"
  )

  const selectedProject = projects?.find((project: any) => project._id === selectedProjectId)
  const selectedSourceIds = selectedProject?.dorkingConfig?.selectedSourceIds || []
  const activeSources = selectedSources?.filter((source: any) =>
    selectedSourceIds.includes(source._id)
  ) || []

  useEffect(() => {
    const stored = localStorage.getItem('productAnalysis')
    if (stored) {
      setAnalysis(JSON.parse(stored))
    }

    fetch('/api/opportunities')
      .then(r => {
        if (r.redirected) {
          router.push('/auth?next=/opportunities')
          return null
        }
        return r.json()
      })
      .then(data => {
        if (data) {
          setPlatforms(data.platforms)
        }
      })
  }, [router])

  useEffect(() => {
    if (!analysis && latestAnalysis) {
      setAnalysis(latestAnalysis as any)
    }
  }, [analysis, latestAnalysis])

  useEffect(() => {
    if (!analysis && latestAnalysis === null) {
      router.push('/onboarding')
    }
  }, [analysis, latestAnalysis, router])

  const togglePlatform = (platformId: string) => {
    setPlatforms(prev => prev.map(p => 
      p.id === platformId ? { ...p, enabled: !p.enabled } : p
    ))
  }

  const toggleStrategy = (strategy: SearchStrategy) => {
    setStrategies(prev => 
      prev.includes(strategy) 
        ? prev.filter(s => s !== strategy)
        : [...prev, strategy]
    )
  }

  const executeSearch = async () => {
    if (!analysis) return
    if (!selectedProjectId) return

    setIsSearching(true)
    setOpportunities([])
    setSearchError('')
    
    try {
      const config = {
        platforms,
        strategies,
        intensity,
        maxResults: intensity === 'broad' ? 80 : intensity === 'balanced' ? 50 : 30
      }

      const response = await fetch('/api/opportunities', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ projectId: selectedProjectId, config })
      })

      if (response.redirected) {
        router.push('/auth?next=/opportunities')
        return
      }

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || 'Failed to search for opportunities')
      }

      if (data.success) {
        const mapped = data.data.opportunities.map((opp: Opportunity) => ({
          ...opp,
          status: 'new',
        }))
        setOpportunities(mapped)
        setGeneratedQueries(data.data.queries)
        setStats(data.data.stats)
        setMissingSources(data.data.missingSources || [])

        await upsertOpportunities({
          projectId: selectedProjectId as any,
          analysisId: latestAnalysis?._id,
          opportunities: mapped.map((opp: Opportunity) => ({
            url: opp.url,
            platform: opp.platform,
            title: opp.title,
            snippet: opp.snippet,
            relevanceScore: opp.relevanceScore,
            intent: opp.intent,
            suggestedApproach: opp.suggestedApproach,
            matchedKeywords: opp.matchedKeywords,
            matchedProblems: opp.matchedProblems,
            softPitch: opp.softPitch,
          })),
        })
      }
    } catch (error: any) {
      console.error('Search error:', error)
      setSearchError(error?.message || 'Search failed. Please try again.')
    } finally {
      setIsSearching(false)
    }
  }

  const generateReply = (opp: Opportunity) => {
    const template = opp.softPitch 
      ? `Hey, I saw your post about ${opp.matchedProblems[0] || 'your challenge'}. We faced something similar and ended up building ${analysis?.productName} specifically for this. Happy to share what worked for us.`
      : `Hi! I noticed you're looking for solutions to ${opp.matchedProblems[0]}. I work on ${analysis?.productName} that helps teams with this - specifically ${opp.matchedKeywords.slice(0, 2).join(' and ')}. Would love to show you how it works.`
    setReplyText(template)
  }

  const getIntentIcon = (intent: string) => {
    switch (intent) {
      case 'frustrated': return <AlertCircle className="h-4 w-4 text-red-400" />
      case 'comparing': return <BarChart3 className="h-4 w-4 text-amber-400" />
      case 'learning': return <Users className="h-4 w-4 text-blue-400" />
      default: return <Target className="h-4 w-4 text-muted-foreground" />
    }
  }

  useEffect(() => {
    if (selectedOpportunity) {
      setStatusInput(selectedOpportunity.status || 'new')
      setNotesInput(selectedOpportunity.notes || '')
      setTagsInput(selectedOpportunity.tags?.join(', ') || '')
    }
  }, [selectedOpportunity])

  const handleSaveOpportunity = async () => {
    if (!selectedOpportunity?.id) return

    const tags = tagsInput
      .split(',')
      .map((tag) => tag.trim())
      .filter(Boolean)

    await updateOpportunity({
      id: selectedOpportunity.id as any,
      status: statusInput,
      notes: notesInput || undefined,
      tags: tags.length > 0 ? tags : undefined,
    })
  }

  if (!analysis) return null

  return (
    <div className="flex h-screen">
      {/* Sidebar */}
      <div className="w-80 border-r border-border bg-card flex flex-col">
        <div className="p-4 border-b border-border">
          <h2 className="font-semibold flex items-center gap-2">
            <Target className="h-5 w-5" />
            Search Configuration
          </h2>
        </div>

        <ScrollArea className="flex-1 p-4 space-y-6">
          {/* Platforms */}
          <div className="space-y-3">
            <Label className="text-sm font-medium uppercase text-muted-foreground">Platforms</Label>
            <div className="space-y-2">
              {platforms.map(platform => (
                <div key={platform.id} className="flex items-center space-x-2">
                  <Checkbox
                    id={platform.id}
                    checked={platform.enabled}
                    onCheckedChange={() => togglePlatform(platform.id)}
                  />
                  <Label htmlFor={platform.id} className="cursor-pointer flex-1">{platform.name}</Label>
                </div>
              ))}
            </div>
          </div>

          <Separator />

          {/* Strategies */}
          <div className="space-y-3">
            <Label className="text-sm font-medium uppercase text-muted-foreground">Strategies</Label>
            <div className="space-y-2">
              {(Object.keys(STRATEGY_INFO) as SearchStrategy[]).map(strategy => (
                <div key={strategy} className="flex items-start space-x-2">
                  <Checkbox
                    id={strategy}
                    checked={strategies.includes(strategy)}
                    onCheckedChange={() => toggleStrategy(strategy)}
                  />
                  <div className="flex-1">
                    <Label htmlFor={strategy} className="cursor-pointer">
                      {STRATEGY_INFO[strategy].name}
                    </Label>
                    <p className="text-xs text-muted-foreground">{STRATEGY_INFO[strategy].description}</p>
                  </div>
                </div>
              ))}
            </div>
          </div>

          <Separator />

          {/* Intensity */}
          <div className="space-y-3">
            <Label className="text-sm font-medium uppercase text-muted-foreground">Intensity</Label>
            <Slider
              value={[intensity === 'broad' ? 0 : intensity === 'balanced' ? 50 : 100]}
              onValueChange={([v]) => setIntensity(v < 33 ? 'broad' : v < 66 ? 'balanced' : 'targeted')}
              max={100}
              step={50}
            />
            <div className="flex justify-between text-xs text-muted-foreground">
              <span>Broad</span>
              <span>Targeted</span>
            </div>
          </div>
        </ScrollArea>

        <div className="p-4 border-t border-border">
          <Button 
            onClick={executeSearch} 
            disabled={
              isSearching ||
              platforms.filter(p => p.enabled).length === 0 ||
              selectedSourceIds.length === 0
            }
            className="w-full"
          >
            {isSearching ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Searching...</> : <><Search className="mr-2 h-4 w-4" /> Find Opportunities</>}
          </Button>
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 overflow-auto p-6">
        <div className="max-w-4xl mx-auto space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-2xl font-bold">Opportunity Finder</h1>
              <p className="text-muted-foreground">Discover potential customers for {analysis.productName}</p>
            </div>
            {stats && (
              <div className="flex gap-4 text-sm">
                <div className="text-center">
                  <div className="font-semibold">{stats.opportunitiesFound}</div>
                  <div className="text-muted-foreground">Found</div>
                </div>
                <div className="text-center">
                  <div className="font-semibold text-green-400">{stats.highRelevance}</div>
                  <div className="text-muted-foreground">High Quality</div>
                </div>
              </div>
            )}
          </div>
          {searchError && (
            <Alert variant="destructive">
              <AlertDescription>{searchError}</AlertDescription>
            </Alert>
          )}

          {/* Active Sources */}
          {activeSources.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="text-sm">Active Data Sources</CardTitle>
                <CardDescription>
                  Sources selected for this project will drive opportunity search.
                </CardDescription>
              </CardHeader>
              <CardContent className="flex flex-wrap gap-2">
                {activeSources.map((source: any) => (
                  <Badge key={source._id} variant="secondary">
                    {source.name || source.url}
                  </Badge>
                ))}
              </CardContent>
            </Card>
          )}

          {selectedSources && selectedSourceIds.length === 0 && (
            <Alert variant="destructive">
              <AlertDescription>
                No data sources selected. Add and select sources to generate opportunities.
              </AlertDescription>
            </Alert>
          )}

          {missingSources.length > 0 && (
            <Alert>
              <AlertDescription>
                Some selected sources don&apos;t have analysis yet. Run onboarding or re-analyze them for best results.
              </AlertDescription>
            </Alert>
          )}

          {/* Generated Queries */}
          {generatedQueries.length > 0 && (
            <Collapsible open={showQueries} onOpenChange={setShowQueries}>
              <Card>
                <CollapsibleTrigger asChild>
                  <CardHeader className="cursor-pointer">
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-sm">Generated Queries ({generatedQueries.length})</CardTitle>
                      {showQueries ? <ChevronUp className="h-4 w-4" /> : <ChevronDown className="h-4 w-4" />}
                    </div>
                  </CardHeader>
                </CollapsibleTrigger>
                <CollapsibleContent>
                  <CardContent>
                    <div className="space-y-1 max-h-48 overflow-auto text-xs font-mono">
                      {generatedQueries.slice(0, 20).map((q, i) => (
                        <div key={i} className="bg-muted px-2 py-1 rounded">{q.query}</div>
                      ))}
                    </div>
                  </CardContent>
                </CollapsibleContent>
              </Card>
            </Collapsible>
          )}

          {/* Results Table */}
          {displayOpportunities.length > 0 ? (
            <Card>
              <div className="flex flex-wrap items-center gap-3 border-b border-border p-4">
                <div className="flex items-center gap-2">
                  <Label className="text-xs text-muted-foreground">Status</Label>
                  <select
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                    className="h-8 rounded-md border border-input bg-background px-2 text-xs"
                  >
                    <option value="all">All</option>
                    <option value="new">New</option>
                    <option value="viewed">Viewed</option>
                    <option value="contacted">Contacted</option>
                    <option value="responded">Responded</option>
                    <option value="converted">Converted</option>
                    <option value="ignored">Ignored</option>
                  </select>
                </div>
                <div className="flex items-center gap-2">
                  <Label className="text-xs text-muted-foreground">Intent</Label>
                  <select
                    value={intentFilter}
                    onChange={(e) => setIntentFilter(e.target.value)}
                    className="h-8 rounded-md border border-input bg-background px-2 text-xs"
                  >
                    <option value="all">All</option>
                    <option value="frustrated">Frustrated</option>
                    <option value="comparing">Comparing</option>
                    <option value="learning">Learning</option>
                    <option value="recommending">Recommending</option>
                    <option value="looking">Looking</option>
                  </select>
                </div>
                <div className="flex items-center gap-2">
                  <Label className="text-xs text-muted-foreground">Min Score</Label>
                  <input
                    type="number"
                    min={0}
                    max={100}
                    value={minScore}
                    onChange={(e) => setMinScore(Number(e.target.value))}
                    className="h-8 w-20 rounded-md border border-input bg-background px-2 text-xs"
                  />
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setLimit((prev) => prev + 50)}
                >
                  Load more
                </Button>
              </div>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Platform</TableHead>
                    <TableHead>Intent</TableHead>
                    <TableHead>Score</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="w-1/2">Post</TableHead>
                    <TableHead>Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {displayOpportunities.slice(0, limit).map((opp) => (
                    <TableRow key={opp.id}>
                      <TableCell><Badge variant="outline">{opp.platform}</Badge></TableCell>
                      <TableCell>
                        <div className="flex items-center gap-2">
                          {getIntentIcon(opp.intent)}
                          <span className="capitalize text-sm">{opp.intent}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge className={opp.relevanceScore >= 0.8 ? 'bg-green-500/20 text-green-400' : opp.relevanceScore >= 0.6 ? 'bg-amber-500/20 text-amber-400' : 'bg-red-500/20 text-red-400'}>
                          {Math.round(opp.relevanceScore * 100)}%
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant="secondary" className="capitalize">
                          {opp.status || 'new'}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <p className="font-medium line-clamp-1">{opp.title}</p>
                        <p className="text-sm text-muted-foreground line-clamp-2">{opp.snippet}</p>
                      </TableCell>
                      <TableCell>
                        <div className="flex gap-1">
                          <Button variant="ghost" size="sm" onClick={() => setSelectedOpportunity(opp)}>
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="sm" onClick={() => window.open(opp.url, '_blank')}>
                            <ExternalLink className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Card>
          ) : isSearching ? (
            <Card className="p-12 text-center">
              <Loader2 className="mx-auto h-12 w-12 text-muted-foreground/50 mb-4 animate-spin" />
              <h3 className="text-lg font-medium">Searching...</h3>
              <p className="text-muted-foreground">Scanning platforms for opportunities</p>
            </Card>
          ) : (
            <Card className="p-12 text-center">
              <Search className="mx-auto h-12 w-12 text-muted-foreground/50 mb-4" />
              <h3 className="text-lg font-medium">Ready to Search</h3>
              <p className="text-muted-foreground">Select platforms and strategies, then click Find Opportunities</p>
            </Card>
          )}
        </div>
      </div>

      {/* Detail Dialog */}
      <Dialog open={!!selectedOpportunity} onOpenChange={() => setSelectedOpportunity(null)}>
        <DialogContent className="max-w-2xl">
          {selectedOpportunity && (
            <>
              <DialogHeader>
                <div className="flex items-center gap-2">
                  <Badge className={selectedOpportunity.relevanceScore >= 0.8 ? 'bg-green-500/20 text-green-400' : selectedOpportunity.relevanceScore >= 0.6 ? 'bg-amber-500/20 text-amber-400' : 'bg-red-500/20 text-red-400'}>
                    {Math.round(selectedOpportunity.relevanceScore * 100)}% Match
                  </Badge>
                  <Badge variant="outline">{selectedOpportunity.platform}</Badge>
                  <Badge variant="secondary" className="capitalize">{selectedOpportunity.intent}</Badge>
                </div>
                <DialogTitle className="text-lg pt-2">{selectedOpportunity.title}</DialogTitle>
                <DialogDescription>{selectedOpportunity.snippet}</DialogDescription>
              </DialogHeader>

              <div className="space-y-4">
                <div className="grid gap-4 md:grid-cols-2">
                  <div className="space-y-2">
                    <Label>Status</Label>
                    <select
                      value={statusInput}
                      onChange={(e) => setStatusInput(e.target.value)}
                      className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
                    >
                      <option value="new">New</option>
                      <option value="viewed">Viewed</option>
                      <option value="contacted">Contacted</option>
                      <option value="responded">Responded</option>
                      <option value="converted">Converted</option>
                      <option value="ignored">Ignored</option>
                    </select>
                  </div>
                  <div className="space-y-2">
                    <Label>Tags (comma separated)</Label>
                    <input
                      value={tagsInput}
                      onChange={(e) => setTagsInput(e.target.value)}
                      className="h-10 w-full rounded-md border border-input bg-background px-3 text-sm"
                      placeholder="reddit, high-intent"
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label>Notes</Label>
                  <Textarea
                    value={notesInput}
                    onChange={(e) => setNotesInput(e.target.value)}
                    placeholder="Add notes about this lead..."
                    rows={3}
                  />
                </div>

                {selectedOpportunity.matchedKeywords.length > 0 && (
                  <div>
                    <Label className="text-sm text-muted-foreground">Matched Keywords</Label>
                    <div className="flex flex-wrap gap-2 mt-1">
                      {selectedOpportunity.matchedKeywords.map((kw, i) => (
                        <Badge key={i} variant="secondary">{kw}</Badge>
                      ))}
                    </div>
                  </div>
                )}

                <div className="bg-muted p-4 rounded-lg">
                  <Label className="text-sm text-muted-foreground">Suggested Approach</Label>
                  <p className="text-sm mt-1">{selectedOpportunity.suggestedApproach}</p>
                </div>

                <div className="space-y-2">
                  <div className="flex items-center justify-between">
                    <Label>Generated Reply</Label>
                    <div className="flex gap-2">
                      <Button variant="outline" size="sm" onClick={() => generateReply(selectedOpportunity)}>
                        <Zap className="h-3 w-3 mr-1" /> Generate
                      </Button>
                      {replyText && (
                        <Button variant="ghost" size="sm" onClick={() => navigator.clipboard.writeText(replyText)}>
                          <Copy className="h-3 w-3 mr-1" /> Copy
                        </Button>
                      )}
                    </div>
                  </div>
                  <Textarea value={replyText} onChange={(e) => setReplyText(e.target.value)} placeholder="Click Generate to create a reply..." rows={4} />
                </div>
              </div>

              <DialogFooter>
                <Button variant="outline" onClick={() => window.open(selectedOpportunity.url, '_blank')}>
                  <ExternalLink className="h-4 w-4 mr-2" /> View Post
                </Button>
                <Button onClick={async () => {
                  await handleSaveOpportunity()
                  setSelectedOpportunity(null)
                }}>
                  <CheckCircle2 className="h-4 w-4 mr-2" /> Save Updates
                </Button>
              </DialogFooter>
            </>
          )}
        </DialogContent>
      </Dialog>
    </div>
  )
}
