"use client"

import { useState, useEffect } from 'react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Badge } from '@/components/ui/badge'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Loader2, Save, AlertTriangle } from 'lucide-react'
import { adminApi } from '@/lib/api/admin'
import { AdminFeature } from '@/types/admin.types'

interface FeatureEditDialogProps {
  feature: AdminFeature
  open: boolean
  onOpenChange: (open: boolean) => void
  onUpdate: (featureId: string, updatedFeature: AdminFeature) => void
}

export function FeatureEditDialog({
  feature,
  open,
  onOpenChange,
  onUpdate
}: FeatureEditDialogProps) {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    complexity: 'medium' as 'low' | 'medium' | 'high',
    business_rules: '',
    technical_requirements: ''
  })
  
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Initialize form data when feature changes
  useEffect(() => {
    if (feature) {
      setFormData({
        name: feature.name || '',
        description: feature.description || '',
        complexity: feature.complexity || 'medium',
        business_rules: feature.business_rules ? JSON.stringify(feature.business_rules, null, 2) : '',
        technical_requirements: feature.technical_requirements ? JSON.stringify(feature.technical_requirements, null, 2) : ''
      })
      setError(null)
    }
  }, [feature])

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (!formData.name.trim()) {
      setError('Feature name is required')
      return
    }

    try {
      setLoading(true)
      setError(null)

      // Prepare update data
      const updateData: Record<string, unknown> = {
        name: formData.name.trim(),
        description: formData.description.trim() || undefined,
        complexity: formData.complexity
      }

      // Parse JSON fields if they have content
      if (formData.business_rules.trim()) {
        try {
          updateData.business_rules = JSON.parse(formData.business_rules)
        } catch (err) {
          setError('Invalid JSON format in business rules')
          return
        }
      }

      if (formData.technical_requirements.trim()) {
        try {
          updateData.technical_requirements = JSON.parse(formData.technical_requirements)
        } catch (err) {
          setError('Invalid JSON format in technical requirements')
          return
        }
      }

      const updatedFeature = await adminApi.updateCustomFeature(feature.id, updateData)
      
      // Update the feature in the parent component
      onUpdate(feature.id, { ...feature, ...updatedFeature })
      
      // Close dialog
      onOpenChange(false)
    } catch (error) {
      console.error('Error updating feature:', error)
    } finally {
      setLoading(false)
    }
  }

  const getComplexityColor = (complexity: string) => {
    switch (complexity) {
      case 'low':
        return 'bg-green-100 text-green-800'
      case 'medium':
        return 'bg-yellow-100 text-yellow-800'
      case 'high':
        return 'bg-red-100 text-red-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>Edit Custom Feature</DialogTitle>
          <p className="text-sm text-gray-600">
            Template: <strong>{feature.template_title || 'Unknown'}</strong>
          </p>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Feature Name */}
          <div className="space-y-2">
            <Label htmlFor="name">Feature Name *</Label>
            <Input
              id="name"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              placeholder="Enter feature name..."
              required
            />
          </div>

          {/* Description */}
          <div className="space-y-2">
            <Label htmlFor="description">Description</Label>
            <Textarea
              id="description"
              value={formData.description}
              onChange={(e) => handleInputChange('description', e.target.value)}
              placeholder="Describe what this feature does..."
              rows={3}
            />
          </div>

          {/* Complexity */}
          <div className="space-y-2">
            <Label htmlFor="complexity">Complexity</Label>
            <Select value={formData.complexity} onValueChange={(value) => handleInputChange('complexity', value)}>
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="low">
                  <div className="flex items-center space-x-2">
                    <Badge className="bg-green-100 text-green-800">Low</Badge>
                    <span>Simple implementation</span>
                  </div>
                </SelectItem>
                <SelectItem value="medium">
                  <div className="flex items-center space-x-2">
                    <Badge className="bg-yellow-100 text-yellow-800">Medium</Badge>
                    <span>Moderate complexity</span>
                  </div>
                </SelectItem>
                <SelectItem value="high">
                  <div className="flex items-center space-x-2">
                    <Badge className="bg-red-100 text-red-800">High</Badge>
                    <span>Complex implementation</span>
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Business Rules */}
          <div className="space-y-2">
            <Label htmlFor="business_rules">Business Rules (JSON)</Label>
            <Textarea
              id="business_rules"
              value={formData.business_rules}
              onChange={(e) => handleInputChange('business_rules', e.target.value)}
              placeholder='{"rule1": "description", "rule2": "description"}'
              rows={4}
            />
            <p className="text-xs text-gray-500">
              Optional: Define business rules for this feature in JSON format
            </p>
          </div>

          {/* Technical Requirements */}
          <div className="space-y-2">
            <Label htmlFor="technical_requirements">Technical Requirements (JSON)</Label>
            <Textarea
              id="technical_requirements"
              value={formData.technical_requirements}
              onChange={(e) => handleInputChange('technical_requirements', e.target.value)}
              placeholder='{"framework": "React", "database": "PostgreSQL"}'
              rows={4}
            />
            <p className="text-xs text-gray-500">
              Optional: Define technical requirements in JSON format
            </p>
          </div>

          {/* Error Display */}
          {error && (
            <Alert>
              <AlertTriangle className="h-4 w-4" />
              <AlertDescription>{error}</AlertDescription>
            </Alert>
          )}

          {/* Action Buttons */}
          <div className="flex justify-end space-x-2 pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
              disabled={loading}
            >
              Cancel
            </Button>
            <Button 
              type="submit" 
              disabled={loading || !formData.name.trim()}
            >
              {loading ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  Updating...
                </>
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  Update Feature
                </>
              )}
            </Button>
          </div>
        </form>
      </DialogContent>
    </Dialog>
  )
}
