"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 { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { 
  Plus, 
  Edit, 
  Trash2, 
  Save, 
  X, 
  Settings,
  Zap,
  AlertCircle,
  CheckCircle,
  RefreshCw
} from 'lucide-react'
import { adminApi, getComplexityColor } from '@/lib/api/admin'
import { AdminFeature, AdminTemplate } from '@/types/admin.types'

interface TemplateFeature {
  id: string
  name: string
  description?: string
  complexity: 'low' | 'medium' | 'high'
  feature_type?: string
  business_rules?: Record<string, unknown>
  technical_requirements?: Record<string, unknown>
  created_at?: string
  updated_at?: string
}

interface TemplateFeaturesManagerProps {
  template: AdminTemplate
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function TemplateFeaturesManager({ template, open, onOpenChange }: TemplateFeaturesManagerProps) {
  const [features, setFeatures] = useState<TemplateFeature[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showAddFeature, setShowAddFeature] = useState(false)
  const [editingFeature, setEditingFeature] = useState<TemplateFeature | null>(null)
  
  // New feature form state
  const [newFeature, setNewFeature] = useState({
    name: '',
    description: '',
    complexity: 'low' as 'low' | 'medium' | 'high',
    feature_type: '',
    business_rules: '',
    technical_requirements: ''
  })

  // Load template features
  const loadFeatures = async () => {
    if (!template.id) return
    
    try {
      setLoading(true)
      setError(null)
      const featuresData = await adminApi.getTemplateFeatures(template.id)
      setFeatures(featuresData as TemplateFeature[])
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load features')
      console.error('Error loading template features:', err)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (open && template.id) {
      loadFeatures()
    }
  }, [open, template.id])

  // Handle add feature
  const handleAddFeature = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!newFeature.name.trim()) {
      alert('Feature name is required')
      return
    }

    try {
      const featureData = {
        name: newFeature.name,
        description: newFeature.description || undefined,
        complexity: newFeature.complexity,
        feature_type: newFeature.feature_type || undefined,
        business_rules: newFeature.business_rules ? JSON.parse(newFeature.business_rules) : undefined,
        technical_requirements: newFeature.technical_requirements ? JSON.parse(newFeature.technical_requirements) : undefined
      }

      const addedFeature = await adminApi.addFeatureToTemplate(template.id, featureData)
      setFeatures(prev => [...prev, addedFeature as TemplateFeature])
      
      // Reset form
      setNewFeature({
        name: '',
        description: '',
        complexity: 'low',
        feature_type: '',
        business_rules: '',
        technical_requirements: ''
      })
      setShowAddFeature(false)
    } catch (err) {
      console.error('Error adding feature:', err)
      alert('Failed to add feature: ' + (err instanceof Error ? err.message : 'Unknown error'))
    }
  }

  // Handle update feature
  const handleUpdateFeature = async (featureId: string, updateData: Partial<TemplateFeature>) => {
    try {
      const updatedFeature = await adminApi.updateTemplateFeature(template.id, featureId, updateData)
      setFeatures(prev => prev.map(f => f.id === featureId ? updatedFeature as TemplateFeature : f))
      setEditingFeature(null)
    } catch (err) {
      console.error('Error updating feature:', err)
      alert('Failed to update feature: ' + (err instanceof Error ? err.message : 'Unknown error'))
    }
  }

  // Handle delete feature
  const handleDeleteFeature = async (featureId: string) => {
    if (!confirm('Are you sure you want to delete this feature?')) return

    try {
      await adminApi.removeFeatureFromTemplate(template.id, featureId)
      setFeatures(prev => prev.filter(f => f.id !== featureId))
    } catch (err) {
      console.error('Error deleting feature:', err)
      alert('Failed to delete feature: ' + (err instanceof Error ? err.message : 'Unknown error'))
    }
  }

  // Handle bulk add common features
  const handleBulkAddCommonFeatures = async () => {
    const commonFeatures = [
      { name: 'User Authentication', description: 'Login and registration system', complexity: 'medium' as const },
      { name: 'Responsive Design', description: 'Mobile-friendly layout', complexity: 'low' as const },
      { name: 'SEO Optimization', description: 'Search engine optimization features', complexity: 'low' as const },
      { name: 'Analytics Integration', description: 'Google Analytics or similar tracking', complexity: 'low' as const },
      { name: 'Contact Form', description: 'Contact form with validation', complexity: 'low' as const },
      { name: 'Content Management', description: 'CMS functionality for content updates', complexity: 'high' as const }
    ]

    try {
      const addedFeatures = await adminApi.bulkAddFeaturesToTemplate(template.id, commonFeatures)
      setFeatures(prev => [...prev, ...addedFeatures as TemplateFeature[]])
    } catch (err) {
      console.error('Error bulk adding features:', err)
      alert('Failed to add common features: ' + (err instanceof Error ? err.message : 'Unknown error'))
    }
  }

  const FeatureCard = ({ feature }: { feature: TemplateFeature }) => (
    <Card className="bg-gray-900 border-gray-800">
      <CardContent className="pt-4">
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <div className="flex items-center space-x-2 mb-2">
              <h4 className="font-medium text-white">{feature.name}</h4>
              <Badge className={getComplexityColor(feature.complexity)}>
                {feature.complexity}
              </Badge>
              {feature.feature_type && (
                <Badge variant="outline" className="text-xs">
                  {feature.feature_type}
                </Badge>
              )}
            </div>
            
            {feature.description && (
              <p className="text-gray-400 text-sm mb-2">{feature.description}</p>
            )}
            
            <div className="text-xs text-gray-500">
              {feature.created_at && `Added: ${new Date(feature.created_at).toLocaleDateString()}`}
            </div>
          </div>
          
          <div className="flex items-center space-x-1">
            <Button
              variant="outline"
              size="sm"
              onClick={() => setEditingFeature(feature)}
              className="text-blue-400 hover:text-blue-300"
            >
              <Edit className="h-3 w-3" />
            </Button>
            <Button
              variant="outline"
              size="sm"
              onClick={() => handleDeleteFeature(feature.id)}
              className="text-red-400 hover:text-red-300"
            >
              <Trash2 className="h-3 w-3" />
            </Button>
          </div>
        </div>
      </CardContent>
    </Card>
  )

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto bg-black border-gray-800">
        <DialogHeader>
          <DialogTitle className="text-white flex items-center space-x-2">
            <Settings className="h-5 w-5" />
            <span>Manage Features - {template.title}</span>
          </DialogTitle>
        </DialogHeader>

        <div className="space-y-6">
          {/* Header Actions */}
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <Zap className="h-5 w-5 text-orange-400" />
              <span className="text-white font-medium">Template Features ({features.length})</span>
            </div>
            <div className="flex items-center space-x-2">
              <Button
                onClick={handleBulkAddCommonFeatures}
                variant="outline"
                size="sm"
                className="text-white border-gray-600 hover:bg-gray-800"
              >
                <Plus className="h-4 w-4 mr-1" />
                Add Common Features
              </Button>
              <Button
                onClick={() => setShowAddFeature(true)}
                className="bg-orange-500 text-black hover:bg-orange-600"
              >
                <Plus className="h-4 w-4 mr-1" />
                Add Feature
              </Button>
              <Button
                onClick={loadFeatures}
                variant="outline"
                size="sm"
                className="text-white border-gray-600 hover:bg-gray-800"
              >
                <RefreshCw className="h-4 w-4" />
              </Button>
            </div>
          </div>

          {/* Loading State */}
          {loading && (
            <div className="flex items-center justify-center py-8">
              <RefreshCw className="h-6 w-6 animate-spin text-orange-400" />
              <span className="ml-2 text-white">Loading features...</span>
            </div>
          )}

          {/* Error State */}
          {error && (
            <Card className="bg-red-900/20 border-red-800">
              <CardContent className="pt-4">
                <div className="flex items-center space-x-2 text-red-400">
                  <AlertCircle className="h-5 w-5" />
                  <span>Error: {error}</span>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Features List */}
          {!loading && !error && (
            <div className="space-y-4">
              {features.length === 0 ? (
                <Card className="bg-gray-900 border-gray-800">
                  <CardContent className="pt-6">
                    <div className="text-center text-gray-400">
                      <Zap className="h-12 w-12 mx-auto mb-4 text-gray-600" />
                      <p>No features added yet</p>
                      <p className="text-sm">Add features to make this template more comprehensive.</p>
                    </div>
                  </CardContent>
                </Card>
              ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {features.map((feature) => (
                    <FeatureCard key={feature.id} feature={feature} />
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Add Feature Form */}
          {showAddFeature && (
            <Card className="bg-gray-900 border-gray-800">
              <CardHeader>
                <CardTitle className="text-white flex items-center justify-between">
                  <span>Add New Feature</span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setShowAddFeature(false)}
                    className="text-gray-400 hover:text-white"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleAddFeature} className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="feature-name" className="text-white">Feature Name *</Label>
                      <Input
                        id="feature-name"
                        value={newFeature.name}
                        onChange={(e) => setNewFeature(prev => ({ ...prev, name: e.target.value }))}
                        className="bg-white/5 border-white/10 text-white"
                        placeholder="e.g., User Authentication"
                        required
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <Label htmlFor="feature-type" className="text-white">Feature Type</Label>
                      <Input
                        id="feature-type"
                        value={newFeature.feature_type}
                        onChange={(e) => setNewFeature(prev => ({ ...prev, feature_type: e.target.value }))}
                        className="bg-white/5 border-white/10 text-white"
                        placeholder="e.g., Authentication, UI, Backend"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="feature-description" className="text-white">Description</Label>
                    <Textarea
                      id="feature-description"
                      value={newFeature.description}
                      onChange={(e) => setNewFeature(prev => ({ ...prev, description: e.target.value }))}
                      className="bg-white/5 border-white/10 text-white"
                      placeholder="Describe what this feature does..."
                      rows={2}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="feature-complexity" className="text-white">Complexity</Label>
                    <Select value={newFeature.complexity} onValueChange={(value) => setNewFeature(prev => ({ ...prev, complexity: value as 'low' | 'medium' | 'high' }))}>
                      <SelectTrigger className="bg-white/5 border-white/10 text-white">
                        <SelectValue placeholder="Select complexity" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="low">Low</SelectItem>
                        <SelectItem value="medium">Medium</SelectItem>
                        <SelectItem value="high">High</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="flex justify-end space-x-2">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setShowAddFeature(false)}
                      className="text-white border-gray-600 hover:bg-gray-800"
                    >
                      Cancel
                    </Button>
                    <Button type="submit" className="bg-orange-500 text-black hover:bg-orange-600">
                      <Save className="h-4 w-4 mr-2" />
                      Add Feature
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          )}

          {/* Edit Feature Dialog */}
          {editingFeature && (
            <Card className="bg-gray-900 border-gray-800">
              <CardHeader>
                <CardTitle className="text-white flex items-center justify-between">
                  <span>Edit Feature</span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setEditingFeature(null)}
                    className="text-gray-400 hover:text-white"
                  >
                    <X className="h-4 w-4" />
                  </Button>
                </CardTitle>
              </CardHeader>
              <CardContent>
                <form onSubmit={(e) => {
                  e.preventDefault()
                  const formData = new FormData(e.currentTarget)
                  handleUpdateFeature(editingFeature.id, {
                    name: formData.get('name') as string,
                    description: formData.get('description') as string,
                    complexity: formData.get('complexity') as 'low' | 'medium' | 'high',
                    feature_type: formData.get('feature_type') as string
                  })
                }} className="space-y-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="space-y-2">
                      <Label htmlFor="edit-name" className="text-white">Feature Name</Label>
                      <Input
                        id="edit-name"
                        name="name"
                        defaultValue={editingFeature.name}
                        className="bg-white/5 border-white/10 text-white"
                        required
                      />
                    </div>
                    
                    <div className="space-y-2">
                      <Label htmlFor="edit-type" className="text-white">Feature Type</Label>
                      <Input
                        id="edit-type"
                        name="feature_type"
                        defaultValue={editingFeature.feature_type || ''}
                        className="bg-white/5 border-white/10 text-white"
                      />
                    </div>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="edit-description" className="text-white">Description</Label>
                    <Textarea
                      id="edit-description"
                      name="description"
                      defaultValue={editingFeature.description || ''}
                      className="bg-white/5 border-white/10 text-white"
                      rows={2}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="edit-complexity" className="text-white">Complexity</Label>
                    <Select name="complexity" defaultValue={editingFeature.complexity}>
                      <SelectTrigger className="bg-white/5 border-white/10 text-white">
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="low">Low</SelectItem>
                        <SelectItem value="medium">Medium</SelectItem>
                        <SelectItem value="high">High</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="flex justify-end space-x-2">
                    <Button
                      type="button"
                      variant="outline"
                      onClick={() => setEditingFeature(null)}
                      className="text-white border-gray-600 hover:bg-gray-800"
                    >
                      Cancel
                    </Button>
                    <Button type="submit" className="bg-orange-500 text-black hover:bg-orange-600">
                      <Save className="h-4 w-4 mr-2" />
                      Update Feature
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}
