'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Skeleton } from '@/components/ui/skeleton'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { ArrowRight, Globe, Loader2, Sparkles, AlertCircle, ArrowLeft } from 'lucide-react'
import type { ProductAnalysis } from '@/lib/types'

const examples = [
  { name: 'Notion', url: 'https://notion.so' },
  { name: 'Stripe', url: 'https://stripe.com' },
  { name: 'Figma', url: 'https://figma.com' },
  { name: 'Linear', url: 'https://linear.app' },
]

export default function OnboardingPage() {
  const router = useRouter()
  const [url, setUrl] = useState('')
  const [loading, setLoading] = useState(false)
  const [progress, setProgress] = useState('')
  const [error, setError] = useState('')
  const [showManualInput, setShowManualInput] = useState(false)

  // Manual input fields
  const [manualProductName, setManualProductName] = useState('')
  const [manualDescription, setManualDescription] = useState('')
  const [manualFeatures, setManualFeatures] = useState('')

  async function analyzeWebsite() {
    if (!url) return

    setLoading(true)
    setError('')
    setProgress('Scraping website...')

    try {
      const response = await fetch('/api/analyze', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ url }),
      })

      const data = await response.json()

      if (!response.ok) {
        if (data.needsManualInput) {
          setShowManualInput(true)
          setManualProductName(url.replace(/^https?:\/\//, '').replace(/\/$/, ''))
          throw new Error(data.error)
        }
        throw new Error(data.error || 'Failed to analyze')
      }

      setProgress('Analyzing with AI...')

      // Store in localStorage for dashboard
      localStorage.setItem('productAnalysis', JSON.stringify(data.data))
      localStorage.setItem('analysisStats', JSON.stringify(data.stats))

      setProgress('Redirecting to dashboard...')

      // Redirect to dashboard with product name in query
      const params = new URLSearchParams({ product: data.data.productName })
      router.push(`/dashboard?${params.toString()}`)
    } catch (err: any) {
      console.error('Analysis error:', err)
      setError(err.message || 'Failed to analyze website')
    } finally {
      setLoading(false)
    }
  }

  async function analyzeManually() {
    if (!manualProductName || !manualDescription) return

    setLoading(true)
    setError('')
    setProgress('Analyzing with AI...')

    try {
      // Create a mock analysis from manual input
      const manualAnalysis: ProductAnalysis = {
        productName: manualProductName,
        tagline: manualDescription.split('.')[0],
        description: manualDescription,
        features: manualFeatures.split('\n').filter(f => f.trim()),
        problemsSolved: [],
        targetAudience: [],
        valuePropositions: [],
        keywords: manualProductName.toLowerCase().split(' '),
        scrapedAt: new Date().toISOString()
      }

      // Send to API to enhance with AI
      const response = await fetch('/api/analyze-manual', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          productName: manualProductName,
          description: manualDescription,
          features: manualFeatures
        }),
      })

      let finalAnalysis = manualAnalysis

      if (response.ok) {
        const data = await response.json()
        finalAnalysis = data.data
      }

      // Store in localStorage for dashboard
      localStorage.setItem('productAnalysis', JSON.stringify(finalAnalysis))
      localStorage.setItem('analysisStats', JSON.stringify({
        features: finalAnalysis.features.length,
        keywords: finalAnalysis.keywords.length,
        personas: finalAnalysis.personas.length,
        useCases: finalAnalysis.useCases.length,
        competitors: finalAnalysis.competitors.length,
        dorkQueries: finalAnalysis.dorkQueries.length
      }))

      // Redirect to dashboard
      const params = new URLSearchParams({ product: finalAnalysis.productName })
      router.push(`/dashboard?${params.toString()}`)
    } catch (err: any) {
      console.error('Manual analysis error:', err)
      setError(err.message || 'Failed to analyze')
    } finally {
      setLoading(false)
    }
  }

  if (showManualInput) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-background p-4">
        <div className="w-full max-w-lg space-y-6">
          <div className="text-center space-y-2">
            <div className="flex justify-center">
              <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-amber-500/20 text-amber-400">
                <AlertCircle className="h-6 w-6" />
              </div>
            </div>
            <h1 className="text-2xl font-bold text-foreground">Couldn&apos;t Reach Website</h1>
            <p className="text-muted-foreground">
              No problem! Tell us about your product and we&apos;ll analyze it manually.
            </p>
          </div>

          {error && (
            <Alert variant="destructive">
              <AlertCircle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          <Card>
            <CardHeader>
              <CardTitle>Describe Your Product</CardTitle>
              <CardDescription>
                Enter your product details and we&apos;ll extract the key information.
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="productName">Product Name *</Label>
                <Input
                  id="productName"
                  placeholder="My Awesome Product"
                  value={manualProductName}
                  onChange={(e) => setManualProductName(e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">Description *</Label>
                <Textarea
                  id="description"
                  placeholder="What does your product do? Who is it for? What problem does it solve?"
                  value={manualDescription}
                  onChange={(e) => setManualDescription(e.target.value)}
                  rows={4}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="features">Key Features (one per line)</Label>
                <Textarea
                  id="features"
                  placeholder="- Feature 1&#10;- Feature 2&#10;- Feature 3"
                  value={manualFeatures}
                  onChange={(e) => setManualFeatures(e.target.value)}
                  rows={4}
                />
              </div>

              {loading && (
                <div className="space-y-3 py-4">
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    {progress}
                  </div>
                  <div className="space-y-2">
                    <Skeleton className="h-4 w-full" />
                    <Skeleton className="h-4 w-4/5" />
                  </div>
                </div>
              )}

              <div className="flex gap-2">
                <Button
                  variant="outline"
                  onClick={() => {
                    setShowManualInput(false)
                    setError('')
                  }}
                  disabled={loading}
                  className="flex-1"
                >
                  <ArrowLeft className="mr-2 h-4 w-4" />
                  Back
                </Button>
                <Button
                  onClick={analyzeManually}
                  disabled={!manualProductName || !manualDescription || loading}
                  className="flex-1 gap-2"
                >
                  {loading ? (
                    <>
                      <Loader2 className="h-4 w-4 animate-spin" />
                      Analyzing...
                    </>
                  ) : (
                    <>
                      Analyze
                      <ArrowRight className="h-4 w-4" />
                    </>
                  )}
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    )
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-background p-4">
      <div className="w-full max-w-lg space-y-6">
        {/* Header */}
        <div className="text-center space-y-2">
          <div className="flex justify-center">
            <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary text-primary-foreground">
              <Sparkles className="h-6 w-6" />
            </div>
          </div>
          <h1 className="text-2xl font-bold text-foreground">Welcome to Sanati</h1>
          <p className="text-muted-foreground">
            Enter your website URL and we&apos;ll analyze your product to find opportunities.
          </p>
        </div>

        {error && (
          <Alert variant="destructive">
            <AlertCircle className="h-4 w-4" />
            <AlertDescription>{error}</AlertDescription>
          </Alert>
        )}

        {/* Input Card */}
        <Card>
          <CardHeader>
            <CardTitle>Analyze Your Product</CardTitle>
            <CardDescription>
              We&apos;ll scrape your site and use AI to extract key information.
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="url">Website URL</Label>
              <div className="relative">
                <Globe className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                <Input
                  id="url"
                  placeholder="https://yourproduct.com"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                  onKeyDown={(e) => e.key === 'Enter' && !loading && analyzeWebsite()}
                  className="pl-10"
                  disabled={loading}
                />
              </div>
            </div>

            {loading && (
              <div className="space-y-3 py-4">
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Loader2 className="h-4 w-4 animate-spin" />
                  {progress}
                </div>
                <div className="space-y-2">
                  <Skeleton className="h-4 w-full" />
                  <Skeleton className="h-4 w-4/5" />
                  <Skeleton className="h-4 w-3/5" />
                </div>
              </div>
            )}

            <Button
              onClick={analyzeWebsite}
              disabled={!url || loading}
              className="w-full gap-2"
            >
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin" />
                  Analyzing...
                </>
              ) : (
                <>
                  Analyze Website
                  <ArrowRight className="h-4 w-4" />
                </>
              )}
            </Button>

            <Button
              variant="ghost"
              size="sm"
              onClick={() => setShowManualInput(true)}
              className="w-full text-muted-foreground"
            >
              Or enter details manually
            </Button>
          </CardContent>
        </Card>

        {/* Examples */}
        <div className="text-center">
          <p className="text-sm text-muted-foreground mb-3">Or try with an example:</p>
          <div className="flex flex-wrap justify-center gap-2">
            {examples.map((example) => (
              <Button
                key={example.url}
                variant="outline"
                size="sm"
                onClick={() => setUrl(example.url)}
                disabled={loading}
              >
                {example.name}
              </Button>
            ))}
          </div>
        </div>
      </div>
    </div>
  )
}
