"use client"

import { useState, useEffect } from 'react'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Checkbox } from '@/components/ui/checkbox'
import { ArrowLeft, Plus, Edit, Trash2 } from 'lucide-react'
import { DatabaseTemplate, TemplateFeature } from '@/lib/template-service'
import { AICustomFeatureCreator } from '@/components/ai/AICustomFeatureCreator'
import { getApiUrl } from '@/config/backend'

interface AdminFeatureSelectionProps {
  template: {
    id: string
    title: string
    description?: string
    type: string
    category?: string
    icon?: string
    gradient?: string
    border?: string
    text?: string
    subtext?: string
  }
  onBack: () => void
}

export function AdminFeatureSelection({ template, onBack }: AdminFeatureSelectionProps) {
  // Admin template service functions using admin API endpoints
  const fetchFeatures = async (templateId: string): Promise<TemplateFeature[]> => {
    const response = await fetch(getApiUrl(`api/templates/${templateId}/features`))
    if (!response.ok) throw new Error('Failed to fetch features')
    const data = await response.json()
    // Handle different response structures
    return Array.isArray(data) ? data : (data.data || data.features || [])
  }

  const createFeature = async (templateId: string, feature: Partial<TemplateFeature>) => {
    const response = await fetch(getApiUrl('api/features'), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...feature, template_id: templateId })
    })
    if (!response.ok) throw new Error('Failed to create feature')
    return response.json()
  }

  const updateFeature = async (templateId: string, featureId: string, feature: Partial<TemplateFeature>) => {
    const response = await fetch(getApiUrl(`api/templates/${templateId}/features/${featureId}`), {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(feature)
    })
    if (!response.ok) throw new Error('Failed to update feature')
    return response.json()
  }

  const deleteFeature = async (templateId: string, featureId: string) => {
    const response = await fetch(getApiUrl(`api/templates/${templateId}/features/${featureId}`), {
      method: 'DELETE'
    })
    if (!response.ok) throw new Error('Failed to delete feature')
  }

  const bulkCreateFeatures = async (templateId: string, features: Partial<TemplateFeature>[]) => {
    const response = await fetch(getApiUrl(`api/templates/${templateId}/features/bulk`), {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ features })
    })
    if (!response.ok) throw new Error('Failed to create features')
    return response.json()
  }

  const [features, setFeatures] = useState<TemplateFeature[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [newFeature, setNewFeature] = useState({ 
    name: '', 
    description: '', 
    complexity: 'medium' as 'low' | 'medium' | 'high' 
  })
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [showAIModal, setShowAIModal] = useState(false)

  const load = async () => {
    try {
      setLoading(true)
      setError(null)
      const data = await fetchFeatures(template.id)
      // Ensure we always have an array
      setFeatures(Array.isArray(data) ? data : [])
    } catch (err) {
      console.error('Error loading features:', err)
      const message = err instanceof Error ? err.message : 'Failed to load features'
      setError(message)
      setFeatures([]) // Reset to empty array on error
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { load() }, [template.id])

  const handleAddCustom = async () => {
    if (!newFeature.name.trim()) return
    
    // Check if template ID is valid UUID format (database templates use UUIDs)
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
    if (!uuidRegex.test(template.id)) {
      alert(`Cannot add features to demo templates. Template ID: ${template.id} is not a valid UUID. Please select a real template from your database.`)
      return
    }
    
    try {
      const created = await createFeature(template.id, {
        name: newFeature.name,
        description: newFeature.description,
        feature_type: 'essential',
        complexity: newFeature.complexity,
        is_default: true,
        created_by_user: true,
      })
      setNewFeature({ name: '', description: '', complexity: 'medium' })
      setSelectedIds((prev) => {
        const next = new Set(prev)
        if (created?.id) next.add(created.id)
        return next
      })
      await load()
    } catch (error) {
      console.error('Error creating custom feature:', error)
      const errorMessage = error instanceof Error ? error.message : 'Template ID not found in database'
      alert(`Failed to create custom feature: ${errorMessage}`)
    }
  }

  const handleAddAIAnalyzed = async (payload: { name: string; description: string; complexity: 'low' | 'medium' | 'high'; logic_rules?: string[]; requirements?: Array<{ text: string; rules: string[] }>; business_rules?: Array<{ requirement: string; rules: string[] }> }) => {
    // Check if template ID is valid UUID format
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
    if (!uuidRegex.test(template.id)) {
      alert("Cannot add features to demo templates. Please select a real template from your database.")
      return
    }
    
    try {
      await createFeature(template.id, {
        name: payload.name,
        description: payload.description,
        feature_type: 'essential',
        complexity: payload.complexity,
        is_default: true,
        created_by_user: true,
        // @ts-expect-error backend accepts additional fields
        logic_rules: payload.logic_rules,
        business_rules: payload.business_rules ?? (payload.requirements ? payload.requirements.map(r => ({ requirement: r.text, rules: r.rules || [] })) : undefined),
      })
      await load()
    } catch (error) {
      console.error('Error creating AI-analyzed feature:', error)
      const errorMessage = error instanceof Error ? error.message : 'Template ID not found in database'
      alert(`Failed to create AI-analyzed feature: ${errorMessage}`)
    }
  }

  const handleUpdate = async (f: TemplateFeature, updates: Partial<TemplateFeature>) => {
    try {
      await updateFeature(template.id, f.id, updates)
      await load()
    } catch (err) {
      console.error('Error updating feature:', err)
      const message = err instanceof Error ? err.message : 'Failed to update feature'
      alert(`Error updating feature: ${message}`)
    }
  }

  const handleDelete = async (f: TemplateFeature) => {
    try {
      await deleteFeature(template.id, f.id)
      setSelectedIds((prev) => {
        const next = new Set(prev)
        next.delete(f.id)
        return next
      })
      await load()
    } catch (err) {
      console.error('Error deleting feature:', err)
      const message = err instanceof Error ? err.message : 'Failed to delete feature'
      alert(`Error deleting feature: ${message}`)
    }
  }

  const toggleSelect = (f: TemplateFeature) => {
    setSelectedIds((prev) => {
      const next = new Set(prev)
      if (next.has(f.id)) next.delete(f.id)
      else next.add(f.id)
      return next
    })
  }

  if (loading) {
    return <div className="text-center py-20 text-white/60">Loading features...</div>
  }
  if (error) {
    return <div className="text-center py-20 text-red-400">{error}</div>
  }

  // Ensure features is always an array before filtering
  const safeFeatures = Array.isArray(features) ? features : []
  const essentialFeatures = safeFeatures.filter(f => f.feature_type === 'essential')
  const suggestedFeatures = safeFeatures.filter(f => f.feature_type === 'suggested')
  const customFeatures = safeFeatures.filter(f => f.feature_type === 'custom')

  const section = (title: string, list: TemplateFeature[]) => (
    <div>
      <h3 className="text-lg font-semibold text-white mb-3">{title} ({list.length})</h3>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {list.map((f) => (
          <Card key={f.id} className={`bg-white/5 ${selectedIds.has(f.id) ? 'border-orange-400' : 'border-white/10'}`}>
            <CardHeader className="pb-3">
              <CardTitle className="text-white flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Checkbox
                    checked={selectedIds.has(f.id)}
                    onCheckedChange={() => toggleSelect(f)}
                    className="border-white/20 data-[state=checked]:bg-orange-500 data-[state=checked]:border-orange-500"
                  />
                  <span>{f.name}</span>
                </div>
                {f.feature_type === 'custom' && (
                  <div className="flex gap-1">
                    <Button
                      size="sm"
                      variant="outline"
                      className="border-blue-500 text-blue-300 hover:bg-blue-500/10"
                      onClick={() => {/* Edit functionality */}}
                    >
                      <Edit className="h-3 w-3" />
                    </Button>
                    <Button
                      size="sm"
                      variant="outline"
                      className="border-red-500 text-red-300 hover:bg-red-500/10"
                      onClick={() => handleDelete(f)}
                    >
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </div>
                )}
              </CardTitle>
            </CardHeader>
            <CardContent className="text-white/80 text-sm space-y-2">
              <p>{f.description || 'No description provided.'}</p>
              <div className="flex gap-2 text-xs">
                <Badge variant="outline" className="bg-white/5 border-white/10">{f.feature_type}</Badge>
                <Badge variant="outline" className="bg-white/5 border-white/10">{f.complexity}</Badge>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )

  return (
    <div className="max-w-7xl mx-auto space-y-8">
      <div className="text-center space-y-4">
        <h1 className="text-4xl font-bold text-white">Select Features for {template.title}</h1>
        <p className="text-xl text-white/60 max-w-3xl mx-auto">Choose defaults or add your own essential features.</p>
      </div>

      {section('Essential Features', essentialFeatures)}
      {section('Suggested Features', suggestedFeatures)}

      <div className="bg-white/5 border border-white/10 rounded-xl p-4 space-y-3">
        <h3 className="text-white font-semibold">Add Essential Feature</h3>
        <p className="text-white/60 text-sm">Use AI to analyze and create essential features for your project.</p>
        <div className="text-center">
          <Button variant="outline" onClick={() => setShowAIModal(true)} className="border-orange-500 text-orange-400 hover:bg-orange-500/10 cursor-pointer">
            <Plus className="h-4 w-4 mr-2" />
            Analyze with AI
          </Button>
        </div>
        <p className="text-white/60 text-xs text-center">AI will analyze your requirements and create essential features</p>
      </div>

      {section('Your Custom Features', customFeatures)}

      {showAIModal && (
        <AICustomFeatureCreator
          projectType={template.type || template.title}
          onAdd={async (f) => { await handleAddAIAnalyzed(f); setShowAIModal(false) }}
          onClose={() => setShowAIModal(false)}
        />
      )}

      <div className="text-center py-4">
        <div className="space-x-4">
          <Button variant="outline" onClick={onBack} className="border-white/20 text-white hover:bg-white/10 cursor-pointer">Back</Button>
        </div>
        <div className="text-white/60 text-sm mt-2">Selected: {selectedIds.size} | Essential: {essentialFeatures.length} | Suggested: {suggestedFeatures.length} | Custom: {customFeatures.length}</div>
      </div>
    </div>
  )
}
