"use client"

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { 
  CheckCircle, 
  AlertTriangle, 
  Loader2, 
  Search,
  Info
} from 'lucide-react'
import { featureApi } from '@/lib/api/admin'
import { FeatureSimilarity, DuplicateCheckResult } from '@/types/admin.types'

interface FeatureSubmissionFormProps {
  templateId: string
  templateName?: string
  onSuccess?: (feature: any) => void
  onCancel?: () => void
}

export function FeatureSubmissionForm({
  templateId,
  templateName,
  onSuccess,
  onCancel
}: FeatureSubmissionFormProps) {
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    complexity: 'medium' as 'low' | 'medium' | 'high',
    business_rules: '',
    technical_requirements: ''
  })
  
  const [submitting, setSubmitting] = useState(false)
  const [similarFeatures, setSimilarFeatures] = useState<FeatureSimilarity[]>([])
  const [duplicateInfo, setDuplicateInfo] = useState<DuplicateCheckResult | null>(null)
  const [searchingSimilar, setSearchingSimilar] = useState(false)
  const [success, setSuccess] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({ ...prev, [field]: value }))
    
    // Clear previous results when name changes
    if (field === 'name') {
      setSimilarFeatures([])
      setDuplicateInfo(null)
    }
  }

  const searchSimilarFeatures = async () => {
    if (!formData.name.trim()) return

    try {
      setSearchingSimilar(true)
      const features = await featureApi.findSimilarFeatures(formData.name, 0.7, 5)
      setSimilarFeatures(features)
      
      // Check if any are potential duplicates
      const potentialDuplicate = features.find(f => f.score >= 0.8)
      if (potentialDuplicate) {
        setDuplicateInfo({
          isDuplicate: true,
          canonicalFeature: potentialDuplicate,
          similarityScore: potentialDuplicate.score,
          matchType: potentialDuplicate.match_type
        })
      } else {
        setDuplicateInfo({ isDuplicate: false })
      }
    } catch (error) {
      console.error('Error searching similar features:', error)
    } finally {
      setSearchingSimilar(false)
    }
  }

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

    try {
      setSubmitting(true)
      setError(null)

      const response = await featureApi.submitCustomFeature({
        template_id: templateId,
        name: formData.name.trim(),
        description: formData.description.trim() || undefined,
        complexity: formData.complexity,
        business_rules: formData.business_rules.trim() ? JSON.parse(formData.business_rules) : undefined,
        technical_requirements: formData.technical_requirements.trim() ? JSON.parse(formData.technical_requirements) : undefined,
        created_by_user_session: 'user-session' // TODO: Get from auth context
      })

      setSuccess(true)
      if (onSuccess) {
        onSuccess(response.data)
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : 'Failed to submit feature')
      console.error('Error submitting feature:', error)
    } finally {
      setSubmitting(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'
    }
  }

  if (success) {
    return (
      <Card>
        <CardContent className="pt-6">
          <div className="text-center">
            <CheckCircle className="h-12 w-12 text-green-600 mx-auto mb-4" />
            <h3 className="text-lg font-semibold mb-2">Feature Submitted Successfully!</h3>
            <p className="text-gray-600 mb-4">
              Your feature "{formData.name}" has been submitted and is pending admin review.
            </p>
            {duplicateInfo?.isDuplicate && (
              <Alert className="mb-4">
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  Similar features were found. An admin will review this submission to determine if it's a duplicate.
                </AlertDescription>
              </Alert>
            )}
            <div className="space-x-2">
              <Button onClick={() => window.location.reload()}>
                Submit Another Feature
              </Button>
              {onCancel && (
                <Button variant="outline" onClick={onCancel}>
                  Close
                </Button>
              )}
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card>
      <CardHeader>
        <CardTitle>Submit Custom Feature</CardTitle>
        {templateName && (
          <p className="text-sm text-gray-600">
            Adding feature to template: <strong>{templateName}</strong>
          </p>
        )}
      </CardHeader>
      <CardContent>
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Feature Name */}
          <div className="space-y-2">
            <Label htmlFor="name">Feature Name *</Label>
            <div className="flex space-x-2">
              <Input
                id="name"
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
                placeholder="Enter feature name..."
                required
              />
              <Button
                type="button"
                variant="outline"
                onClick={searchSimilarFeatures}
                disabled={!formData.name.trim() || searchingSimilar}
              >
                {searchingSimilar ? (
                  <Loader2 className="h-4 w-4 animate-spin" />
                ) : (
                  <Search className="h-4 w-4" />
                )}
              </Button>
            </div>
          </div>

          {/* Similar Features Alert */}
          {similarFeatures.length > 0 && (
            <Alert>
              <Info className="h-4 w-4" />
              <AlertDescription>
                <div className="space-y-2">
                  <p>Similar features found:</p>
                  <div className="space-y-1">
                    {similarFeatures.map((feature) => (
                      <div key={feature.id} className="flex items-center justify-between text-sm">
                        <span>{feature.name}</span>
                        <Badge variant="outline">
                          {(feature.score * 100).toFixed(1)}% match
                        </Badge>
                      </div>
                    ))}
                  </div>
                  {duplicateInfo?.isDuplicate && (
                    <p className="text-amber-600 font-medium mt-2">
                      ⚠️ This may be a duplicate. Please review before submitting.
                    </p>
                  )}
                </div>
              </AlertDescription>
            </Alert>
          )}

          {/* 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={3}
            />
            <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={3}
            />
            <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>
          )}

          {/* Submit Button */}
          <div className="flex space-x-2">
            <Button 
              type="submit" 
              disabled={submitting || !formData.name.trim()}
              className="flex-1"
            >
              {submitting ? (
                <>
                  <Loader2 className="h-4 w-4 animate-spin mr-2" />
                  Submitting...
                </>
              ) : (
                'Submit Feature'
              )}
            </Button>
            {onCancel && (
              <Button type="button" variant="outline" onClick={onCancel}>
                Cancel
              </Button>
            )}
          </div>
        </form>
      </CardContent>
    </Card>
  )
}
