"use client"

import React, { useState } from "react"
import { motion, AnimatePresence } from "framer-motion"
import { useForm } from "react-hook-form"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "../ui/card"
import { Button } from "../ui/button"
import { Input } from "../ui/input"
import { Label } from "../ui/label"
import { Textarea } from "../ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select"
import { Checkbox } from "../ui/checkbox"
import { Switch } from "../ui/switch"
import { MoonUIBadgePro as Badge } from "../ui/badge"
import { cn } from "../../lib/utils"
import { Lock, Sparkles, CheckCircle, AlertCircle, Eye, EyeOff, Upload, X } from "lucide-react"
import { useSubscription } from "../../hooks/use-subscription"

interface AdvancedFormField {
  name: string
  label: string
  type: "text" | "email" | "password" | "textarea" | "select" | "checkbox" | "switch" | "file" | "number" | "url" | "tel"
  placeholder?: string
  required?: boolean
  options?: Array<{ value: string; label: string }>
  validation?: {
    minLength?: number
    maxLength?: number
    pattern?: RegExp
    custom?: (value: any) => string | true
  }
  description?: string
  defaultValue?: any
}

interface AdvancedFormsProps {
  fields: AdvancedFormField[]
  onSubmit: (data: any) => void | Promise<void>
  title?: string
  description?: string
  submitText?: string
  enableAutoSave?: boolean
  showProgress?: boolean
  className?: string
  layout?: "vertical" | "horizontal" | "grid"
  columns?: number
}

const AdvancedFormsInternal: React.FC<AdvancedFormsProps> = ({
  fields,
  onSubmit,
  title = "Advanced Form",
  description,
  submitText = "Submit",
  enableAutoSave = false,
  showProgress = true,
  className,
  layout = "vertical",
  columns = 2
}) => {
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>({})
  const [uploadedFiles, setUploadedFiles] = useState<Record<string, File[]>>({})
  
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isValid, touchedFields },
    setValue,
    getValues
  } = useForm<any>({
    mode: "onChange",
    defaultValues: fields.reduce((acc, field) => ({
      ...acc,
      [field.name]: field.defaultValue || (field.type === "checkbox" ? false : "")
    }), {})
  })

  const watchedValues = watch()
  const completedFields = Object.keys(touchedFields).length
  const progress = fields.length > 0 ? (completedFields / fields.length) * 100 : 0

  const handleFormSubmit = async (data: any) => {
    setIsSubmitting(true)
    try {
      await onSubmit(data)
    } finally {
      setIsSubmitting(false)
    }
  }

  const togglePasswordVisibility = (fieldName: string) => {
    setShowPasswords(prev => ({
      ...prev,
      [fieldName]: !prev[fieldName]
    }))
  }

  const handleFileUpload = (fieldName: string, files: FileList | null) => {
    if (files) {
      const fileArray = Array.from(files)
      setUploadedFiles(prev => ({
        ...prev,
        [fieldName]: fileArray
      }))
      setValue(fieldName as any, fileArray as any)
    }
  }

  const removeFile = (fieldName: string, index: number) => {
    setUploadedFiles(prev => {
      const newFiles = [...(prev[fieldName] || [])]
      newFiles.splice(index, 1)
      return {
        ...prev,
        [fieldName]: newFiles
      }
    })
    setValue(fieldName as any, uploadedFiles[fieldName]?.filter((_, i) => i !== index) || [] as any)
  }

  const renderField = (field: AdvancedFormField, index: number) => {
    const error = errors[field.name]
    const isTouched = touchedFields[field.name]
    
    return (
      <motion.div
        key={field.name}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: index * 0.1 }}
        className="space-y-2"
      >
        <div className="flex items-center justify-between">
          <Label htmlFor={field.name} className="flex items-center gap-2">
            {field.label}
            {field.required && <span className="text-destructive">*</span>}
            {isTouched && !error && (
              <CheckCircle className="h-4 w-4 text-green-500" />
            )}
            {error && <AlertCircle className="h-4 w-4 text-destructive" />}
          </Label>
        </div>

        <div className="relative">
          {field.type === "text" || field.type === "email" || field.type === "number" || field.type === "url" || field.type === "tel" && (
            <Input
              id={field.name}
              type={field.type}
              placeholder={field.placeholder}
              className={cn(error && "border-destructive")}
              {...register(field.name, {
                required: field.required ? `${field.label} is required` : false,
                minLength: field.validation?.minLength ? {
                  value: field.validation.minLength,
                  message: `Minimum ${field.validation.minLength} characters required`
                } : undefined,
                maxLength: field.validation?.maxLength ? {
                  value: field.validation.maxLength,
                  message: `Maximum ${field.validation.maxLength} characters allowed`
                } : undefined,
                pattern: field.validation?.pattern ? {
                  value: field.validation.pattern,
                  message: "Invalid format"
                } : undefined,
                validate: field.validation?.custom
              })}
            />
          )}

          {field.type === "password" && (
            <div className="relative">
              <Input
                id={field.name}
                type={showPasswords[field.name] ? "text" : "password"}
                placeholder={field.placeholder}
                className={cn("pr-10", error && "border-destructive")}
                {...register(field.name, {
                  required: field.required ? `${field.label} is required` : false,
                  minLength: field.validation?.minLength ? {
                    value: field.validation.minLength,
                    message: `Minimum ${field.validation.minLength} characters required`
                  } : undefined
                })}
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-1 top-1/2 -translate-y-1/2 h-8 w-8 p-0"
                onClick={() => togglePasswordVisibility(field.name)}
              >
                {showPasswords[field.name] ? (
                  <EyeOff className="h-4 w-4" />
                ) : (
                  <Eye className="h-4 w-4" />
                )}
              </Button>
            </div>
          )}

          {field.type === "textarea" && (
            <Textarea
              id={field.name}
              placeholder={field.placeholder}
              className={cn(error && "border-destructive")}
              rows={3}
              {...register(field.name, {
                required: field.required ? `${field.label} is required` : false,
                maxLength: field.validation?.maxLength ? {
                  value: field.validation.maxLength,
                  message: `Maximum ${field.validation.maxLength} characters allowed`
                } : undefined
              })}
            />
          )}

          {field.type === "select" && (
            <Select
              onValueChange={(value) => setValue(field.name, value)}
              defaultValue={field.defaultValue}
            >
              <SelectTrigger className={cn(error && "border-destructive")}>
                <SelectValue placeholder={field.placeholder} />
              </SelectTrigger>
              <SelectContent>
                {field.options?.map((option) => (
                  <SelectItem key={option.value} value={option.value}>
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}

          {field.type === "checkbox" && (
            <div className="flex items-center space-x-2">
              <Checkbox
                id={field.name}
                {...register(field.name)}
                onCheckedChange={(checked: boolean) => setValue(field.name, checked)}
              />
              <Label htmlFor={field.name} className="text-sm">
                {field.placeholder || "Check this option"}
              </Label>
            </div>
          )}

          {field.type === "switch" && (
            <div className="flex items-center space-x-2">
              <Switch
                id={field.name}
                {...register(field.name)}
                onCheckedChange={(checked: boolean) => setValue(field.name, checked)}
              />
              <Label htmlFor={field.name} className="text-sm">
                {field.placeholder || "Toggle this option"}
              </Label>
            </div>
          )}

          {field.type === "file" && (
            <div className="space-y-2">
              <div className="flex items-center justify-center w-full">
                <label
                  htmlFor={field.name}
                  className="flex flex-col items-center justify-center w-full h-32 border-2 border-dashed rounded-lg cursor-pointer bg-muted/50 hover:bg-muted/80 transition-colors"
                >
                  <div className="flex flex-col items-center justify-center pt-5 pb-6">
                    <Upload className="w-8 h-8 mb-4 text-muted-foreground" />
                    <p className="mb-2 text-sm text-muted-foreground">
                      <span className="font-semibold">Click to upload</span> or drag and drop
                    </p>
                  </div>
                  <input
                    id={field.name}
                    type="file"
                    multiple
                    className="hidden"
                    onChange={(e) => handleFileUpload(field.name, e.target.files)}
                  />
                </label>
              </div>
              
              {uploadedFiles[field.name] && uploadedFiles[field.name].length > 0 && (
                <div className="space-y-2">
                  {uploadedFiles[field.name].map((file, index) => (
                    <div key={index} className="flex items-center justify-between p-2 bg-muted rounded-md">
                      <span className="text-sm truncate">{file.name}</span>
                      <Button
                        type="button"
                        variant="ghost"
                        size="sm"
                        onClick={() => removeFile(field.name, index)}
                      >
                        <X className="h-4 w-4" />
                      </Button>
                    </div>
                  ))}
                </div>
              )}
            </div>
          )}
        </div>

        {field.description && (
          <p className="text-sm text-muted-foreground">{field.description}</p>
        )}

        <AnimatePresence>
          {error && (
            <motion.p
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: "auto" }}
              exit={{ opacity: 0, height: 0 }}
              className="text-sm text-destructive"
            >
              {error.message as string}
            </motion.p>
          )}
        </AnimatePresence>
      </motion.div>
    )
  }

  const gridClassName = layout === "grid" ? `grid grid-cols-1 md:grid-cols-${columns} gap-6` : "space-y-6"

  return (
    <Card className={cn("w-full max-w-4xl", className)}>
      <CardHeader>
        <div className="flex items-center justify-between">
          <div>
            <CardTitle>{title}</CardTitle>
            {description && <CardDescription>{description}</CardDescription>}
          </div>
          <Badge variant="pro" className="ml-2">
            PRO
          </Badge>
        </div>
        
        {showProgress && (
          <div className="space-y-2">
            <div className="flex justify-between text-sm">
              <span>Progress</span>
              <span>{Math.round(progress)}%</span>
            </div>
            <div className="w-full bg-muted rounded-full h-2">
              <motion.div
                className="bg-primary h-2 rounded-full"
                initial={{ width: 0 }}
                animate={{ width: `${progress}%` }}
                transition={{ duration: 0.3 }}
              />
            </div>
          </div>
        )}
      </CardHeader>
      
      <CardContent>
        <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-6">
          <div className={gridClassName}>
            {fields.map((field, index) => renderField(field, index))}
          </div>
          
          <div className="flex items-center justify-between pt-6">
            <div className="text-sm text-muted-foreground">
              {completedFields}/{fields.length} fields completed
            </div>
            
            <Button
              type="submit"
              disabled={isSubmitting || !isValid}
              className="min-w-32"
            >
              {isSubmitting ? (
                <motion.div
                  animate={{ rotate: 360 }}
                  transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
                  className="w-4 h-4 border-2 border-white border-t-transparent rounded-full"
                />
              ) : (
                submitText
              )}
            </Button>
          </div>
        </form>
      </CardContent>
    </Card>
  )
}

export const AdvancedForms: React.FC<AdvancedFormsProps> = ({ className, ...props }) => {
  const { hasProAccess, isLoading } = useSubscription()
  
  // If no pro access, show upgrade prompt
  if (!isLoading && !hasProAccess) {
    return (
      <Card className={cn("w-fit", className)}>
        <CardContent className="py-6 text-center">
          <div className="space-y-4">
            <div className="rounded-full bg-purple-100 dark:bg-purple-900/30 p-3 w-fit mx-auto">
              <Lock className="h-6 w-6 text-purple-600 dark:text-purple-400" />
            </div>
            <div>
              <h3 className="font-semibold text-sm mb-2">Pro Feature</h3>
              <p className="text-muted-foreground text-xs mb-4">
                Advanced Forms is available exclusively to MoonUI Pro subscribers.
              </p>
              <a href="/pricing">
                <Button size="sm">
                  <Sparkles className="mr-2 h-4 w-4" />
                  Upgrade to Pro
                </Button>
              </a>
            </div>
          </div>
        </CardContent>
      </Card>
    )
  }

  return <AdvancedFormsInternal className={className} {...props} />
}

export type { AdvancedFormField, AdvancedFormsProps }