import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { 
  FileText, 
  Plus, 
  Edit, 
  Trash2, 
  Save,
  Eye,
  Copy,
  Download,
  Upload,
  Settings,
  Palette,
  Layout,
  Type,
  Calendar,
  Mail,
  Phone,
  Hash,
  ToggleLeft,
  CheckSquare,
  List,
  Image,
  MapPin,
  Star,
  Globe,
  Languages,
  Smartphone
} from "lucide-react";

// 18 Form Design Templates
const formDesigns = [
  {
    id: 1,
    name: "modern-gradient",
    displayName: "Modern Gradient",
    description: "Sleek design with gradient backgrounds",
    category: "business",
    preview: "bg-gradient-to-br from-blue-500 to-purple-600",
    features: ["Gradient backgrounds", "Rounded corners", "Shadow effects"]
  },
  {
    id: 2,
    name: "minimalist-clean",
    displayName: "Minimalist Clean",
    description: "Clean and simple design",
    category: "general",
    preview: "bg-white border border-gray-200",
    features: ["Clean lines", "Minimal styling", "Focus on content"]
  },
  {
    id: 3,
    name: "sports-dynamic",
    displayName: "Sports Dynamic",
    description: "Energetic design for sports forms",
    category: "sports",
    preview: "bg-gradient-to-r from-green-400 to-blue-500",
    features: ["Dynamic colors", "Athletic styling", "Action-oriented"]
  },
  {
    id: 4,
    name: "corporate-professional",
    displayName: "Corporate Professional",
    description: "Professional design for business use",
    category: "business",
    preview: "bg-gradient-to-br from-gray-600 to-gray-800",
    features: ["Professional styling", "Corporate colors", "Formal layout"]
  },
  {
    id: 5,
    name: "creative-colorful",
    displayName: "Creative Colorful",
    description: "Vibrant and creative design",
    category: "creative",
    preview: "bg-gradient-to-r from-pink-400 via-purple-500 to-indigo-500",
    features: ["Vibrant colors", "Creative layouts", "Artistic elements"]
  },
  {
    id: 6,
    name: "education-friendly",
    displayName: "Education Friendly",
    description: "Designed for educational institutions",
    category: "education",
    preview: "bg-gradient-to-br from-yellow-400 to-orange-500",
    features: ["Educational colors", "Student-friendly", "Clear navigation"]
  },
  {
    id: 7,
    name: "healthcare-calm",
    displayName: "Healthcare Calm",
    description: "Calming design for healthcare forms",
    category: "healthcare",
    preview: "bg-gradient-to-r from-teal-400 to-cyan-500",
    features: ["Calming colors", "Medical styling", "Trustworthy design"]
  },
  {
    id: 8,
    name: "event-festive",
    displayName: "Event Festive",
    description: "Festive design for event registrations",
    category: "events",
    preview: "bg-gradient-to-br from-red-400 to-pink-500",
    features: ["Festive colors", "Event styling", "Celebration theme"]
  },
  {
    id: 9,
    name: "tech-futuristic",
    displayName: "Tech Futuristic",
    description: "Futuristic design for tech companies",
    category: "technology",
    preview: "bg-gradient-to-r from-indigo-500 to-purple-600",
    features: ["Futuristic styling", "Tech colors", "Modern elements"]
  },
  {
    id: 10,
    name: "nature-organic",
    displayName: "Nature Organic",
    description: "Natural and organic design",
    category: "environment",
    preview: "bg-gradient-to-br from-green-500 to-emerald-600",
    features: ["Natural colors", "Organic shapes", "Eco-friendly"]
  },
  {
    id: 11,
    name: "luxury-elegant",
    displayName: "Luxury Elegant",
    description: "Elegant design for luxury brands",
    category: "luxury",
    preview: "bg-gradient-to-r from-amber-400 to-yellow-500",
    features: ["Luxury styling", "Elegant typography", "Premium feel"]
  },
  {
    id: 12,
    name: "startup-bold",
    displayName: "Startup Bold",
    description: "Bold design for startups",
    category: "startup",
    preview: "bg-gradient-to-br from-violet-500 to-purple-600",
    features: ["Bold colors", "Startup vibe", "Innovative design"]
  },
  {
    id: 13,
    name: "dark-mode",
    displayName: "Dark Mode",
    description: "Dark theme design",
    category: "general",
    preview: "bg-gradient-to-r from-gray-800 to-gray-900",
    features: ["Dark theme", "Modern styling", "Eye-friendly"]
  },
  {
    id: 14,
    name: "glass-morphism",
    displayName: "Glass Morphism",
    description: "Glassmorphism design trend",
    category: "modern",
    preview: "bg-gradient-to-br from-blue-400/20 to-purple-500/20 backdrop-blur",
    features: ["Glass effect", "Transparency", "Modern trend"]
  },
  {
    id: 15,
    name: "retro-vintage",
    displayName: "Retro Vintage",
    description: "Vintage and retro styling",
    category: "vintage",
    preview: "bg-gradient-to-r from-orange-400 to-red-500",
    features: ["Retro colors", "Vintage styling", "Classic feel"]
  },
  {
    id: 16,
    name: "survey-simple",
    displayName: "Survey Simple",
    description: "Simple design for surveys",
    category: "survey",
    preview: "bg-gradient-to-br from-gray-100 to-gray-200",
    features: ["Simple layout", "Survey optimized", "Clear questions"]
  },
  {
    id: 17,
    name: "mobile-first",
    displayName: "Mobile First",
    description: "Optimized for mobile devices",
    category: "mobile",
    preview: "bg-gradient-to-b from-blue-500 to-indigo-600",
    features: ["Mobile optimized", "Touch-friendly", "Responsive design"]
  },
  {
    id: 18,
    name: "accessibility-focused",
    displayName: "Accessibility Focused",
    description: "High contrast and accessible design",
    category: "accessibility",
    preview: "bg-gradient-to-r from-black to-gray-700",
    features: ["High contrast", "Screen reader friendly", "Accessible design"]
  }
];

const fieldTypes = [
  { type: "text", label: "Text Input", icon: Type },
  { type: "email", label: "Email", icon: Mail },
  { type: "phone", label: "Phone", icon: Phone },
  { type: "number", label: "Number", icon: Hash },
  { type: "textarea", label: "Text Area", icon: FileText },
  { type: "select", label: "Dropdown", icon: List },
  { type: "checkbox", label: "Checkbox", icon: CheckSquare },
  { type: "radio", label: "Radio Button", icon: ToggleLeft },
  { type: "date", label: "Date Picker", icon: Calendar },
  { type: "file", label: "File Upload", icon: Upload },
  { type: "url", label: "Website URL", icon: Globe },
  { type: "location", label: "Location", icon: MapPin },
  { type: "rating", label: "Rating", icon: Star }
];

export default function FormBuilder() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedDesign, setSelectedDesign] = useState(formDesigns[0]);
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [formFields, setFormFields] = useState([]);
  const [formSettings, setFormSettings] = useState({
    title: "New Form",
    description: "",
    language: "en",
    rtl: false,
    emailNotifications: false,
    emailTemplate: "",
    recipients: [],
    requireAuth: false,
    allowAnonymous: true,
    multiPage: false,
    progressBar: true
  });

  const categories = [
    "all", "business", "sports", "education", "healthcare", 
    "events", "technology", "creative", "general"
  ];

  const filteredDesigns = selectedCategory === "all" 
    ? formDesigns 
    : formDesigns.filter(design => design.category === selectedCategory);

  const addField = (fieldType) => {
    const newField = {
      id: Date.now().toString(),
      type: fieldType.type,
      label: fieldType.label,
      placeholder: "",
      required: false,
      validation: {},
      options: fieldType.type === "select" || fieldType.type === "radio" ? ["Option 1", "Option 2"] : []
    };
    setFormFields([...formFields, newField]);
  };

  const updateField = (fieldId, updates) => {
    setFormFields(formFields.map(field => 
      field.id === fieldId ? { ...field, ...updates } : field
    ));
  };

  const removeField = (fieldId) => {
    setFormFields(formFields.filter(field => field.id !== fieldId));
  };

  const moveField = (fieldId, direction) => {
    const currentIndex = formFields.findIndex(field => field.id === fieldId);
    if (direction === "up" && currentIndex > 0) {
      const newFields = [...formFields];
      [newFields[currentIndex], newFields[currentIndex - 1]] = [newFields[currentIndex - 1], newFields[currentIndex]];
      setFormFields(newFields);
    } else if (direction === "down" && currentIndex < formFields.length - 1) {
      const newFields = [...formFields];
      [newFields[currentIndex], newFields[currentIndex + 1]] = [newFields[currentIndex + 1], newFields[currentIndex]];
      setFormFields(newFields);
    }
  };

  const saveForm = () => {
    const formData = {
      ...formSettings,
      design: selectedDesign.name,
      fields: formFields,
      createdAt: new Date().toISOString()
    };
    
    // Save to localStorage for now (in real app, save to database)
    const savedForms = JSON.parse(localStorage.getItem('savedForms') || '[]');
    savedForms.push(formData);
    localStorage.setItem('savedForms', JSON.stringify(savedForms));
    
    toast({ title: "Form saved successfully" });
  };

  const previewForm = () => {
    toast({ title: "Opening form preview", description: "Form preview will open in a new window" });
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Form Builder</h1>
          <p className="text-muted-foreground">
            Create beautiful forms with 18 different designs and advanced features
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <Badge variant="secondary" className="flex items-center space-x-1">
            <Palette className="h-3 w-3" />
            <span>18 Designs</span>
          </Badge>
          <Button onClick={previewForm} variant="outline" className="flex items-center space-x-2">
            <Eye className="h-4 w-4" />
            <span>Preview</span>
          </Button>
          <Button onClick={saveForm} className="flex items-center space-x-2">
            <Save className="h-4 w-4" />
            <span>Save Form</span>
          </Button>
        </div>
      </div>

      <Tabs defaultValue="design" className="w-full">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="design">Design</TabsTrigger>
          <TabsTrigger value="fields">Fields</TabsTrigger>
          <TabsTrigger value="settings">Settings</TabsTrigger>
          <TabsTrigger value="preview">Preview</TabsTrigger>
        </TabsList>

        <TabsContent value="design" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Choose Form Design</CardTitle>
              <CardDescription>
                Select from 18 beautiful form designs optimized for different use cases
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {/* Category Filter */}
                <div className="flex items-center space-x-2 overflow-x-auto pb-2">
                  {categories.map((category) => (
                    <Button
                      key={category}
                      size="sm"
                      variant={selectedCategory === category ? "default" : "outline"}
                      onClick={() => setSelectedCategory(category)}
                      className="whitespace-nowrap"
                    >
                      {category.charAt(0).toUpperCase() + category.slice(1)}
                    </Button>
                  ))}
                </div>

                {/* Design Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {filteredDesigns.map((design) => (
                    <div
                      key={design.id}
                      className={`border rounded-lg p-4 cursor-pointer transition-all ${
                        selectedDesign.id === design.id
                          ? "border-primary bg-primary/5 ring-2 ring-primary/20"
                          : "border-gray-200 hover:border-gray-300"
                      }`}
                      onClick={() => setSelectedDesign(design)}
                    >
                      {/* Preview */}
                      <div className={`h-24 rounded-lg mb-3 ${design.preview} flex items-center justify-center`}>
                        <div className="w-16 h-12 bg-white/20 rounded border border-white/30 flex items-center justify-center">
                          <FileText className="h-6 w-6 text-white" />
                        </div>
                      </div>
                      
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <h3 className="font-medium">{design.displayName}</h3>
                          <Badge variant="outline" className="text-xs">
                            {design.category}
                          </Badge>
                        </div>
                        <p className="text-sm text-muted-foreground">{design.description}</p>
                        <div className="flex flex-wrap gap-1">
                          {design.features.slice(0, 2).map((feature, index) => (
                            <Badge key={index} variant="secondary" className="text-xs">
                              {feature}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="fields" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Field Types */}
            <Card>
              <CardHeader>
                <CardTitle>Field Types</CardTitle>
                <CardDescription>Drag or click to add fields to your form</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 gap-2">
                  {fieldTypes.map((fieldType) => {
                    const Icon = fieldType.icon;
                    return (
                      <Button
                        key={fieldType.type}
                        variant="outline"
                        className="h-auto p-3 flex flex-col items-center space-y-2"
                        onClick={() => addField(fieldType)}
                      >
                        <Icon className="h-5 w-5" />
                        <span className="text-xs text-center">{fieldType.label}</span>
                      </Button>
                    );
                  })}
                </div>
              </CardContent>
            </Card>

            {/* Form Structure */}
            <Card>
              <CardHeader>
                <CardTitle>Form Structure</CardTitle>
                <CardDescription>
                  Configure your form fields ({formFields.length} fields)
                </CardDescription>
              </CardHeader>
              <CardContent>
                {formFields.length === 0 ? (
                  <div className="text-center py-8 text-muted-foreground">
                    No fields added yet. Click on field types to add them.
                  </div>
                ) : (
                  <div className="space-y-3">
                    {formFields.map((field, index) => {
                      const Icon = fieldTypes.find(ft => ft.type === field.type)?.icon || Type;
                      return (
                        <div key={field.id} className="border rounded-lg p-3">
                          <div className="flex items-center justify-between mb-2">
                            <div className="flex items-center space-x-2">
                              <Icon className="h-4 w-4" />
                              <span className="font-medium">{field.label}</span>
                              {field.required && (
                                <Badge variant="secondary" className="text-xs">Required</Badge>
                              )}
                            </div>
                            <div className="flex items-center space-x-1">
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => moveField(field.id, "up")}
                                disabled={index === 0}
                                className="h-6 w-6 p-0"
                              >
                                ↑
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => moveField(field.id, "down")}
                                disabled={index === formFields.length - 1}
                                className="h-6 w-6 p-0"
                              >
                                ↓
                              </Button>
                              <Button
                                size="sm"
                                variant="ghost"
                                onClick={() => removeField(field.id)}
                                className="h-6 w-6 p-0"
                              >
                                <Trash2 className="h-3 w-3" />
                              </Button>
                            </div>
                          </div>
                          <div className="grid grid-cols-2 gap-2 text-sm">
                            <div>
                              <Label className="text-xs">Label</Label>
                              <Input
                                value={field.label}
                                onChange={(e) => updateField(field.id, { label: e.target.value })}
                                className="h-8"
                              />
                            </div>
                            <div>
                              <Label className="text-xs">Placeholder</Label>
                              <Input
                                value={field.placeholder}
                                onChange={(e) => updateField(field.id, { placeholder: e.target.value })}
                                className="h-8"
                              />
                            </div>
                          </div>
                          <div className="flex items-center space-x-2 mt-2">
                            <Switch
                              checked={field.required}
                              onCheckedChange={(checked) => updateField(field.id, { required: checked })}
                            />
                            <Label className="text-xs">Required field</Label>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="settings" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Form Settings */}
            <Card>
              <CardHeader>
                <CardTitle>Form Settings</CardTitle>
                <CardDescription>Configure basic form settings</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <Label>Form Title</Label>
                  <Input
                    value={formSettings.title}
                    onChange={(e) => setFormSettings(prev => ({ ...prev, title: e.target.value }))}
                  />
                </div>
                <div>
                  <Label>Description</Label>
                  <Textarea
                    value={formSettings.description}
                    onChange={(e) => setFormSettings(prev => ({ ...prev, description: e.target.value }))}
                    placeholder="Form description"
                  />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div>
                    <Label>Language</Label>
                    <Select
                      value={formSettings.language}
                      onValueChange={(value) => setFormSettings(prev => ({ ...prev, language: value }))}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="en">English</SelectItem>
                        <SelectItem value="es">Spanish</SelectItem>
                        <SelectItem value="fr">French</SelectItem>
                        <SelectItem value="de">German</SelectItem>
                        <SelectItem value="ar">Arabic</SelectItem>
                        <SelectItem value="zh">Chinese</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="flex items-center space-x-2 pt-6">
                    <Switch
                      checked={formSettings.rtl}
                      onCheckedChange={(checked) => setFormSettings(prev => ({ ...prev, rtl: checked }))}
                    />
                    <Label>RTL Support</Label>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Notifications & Security */}
            <Card>
              <CardHeader>
                <CardTitle>Notifications & Security</CardTitle>
                <CardDescription>Configure email notifications and security</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center space-x-2">
                  <Switch
                    checked={formSettings.emailNotifications}
                    onCheckedChange={(checked) => setFormSettings(prev => ({ ...prev, emailNotifications: checked }))}
                  />
                  <Label>Email notifications on submission</Label>
                </div>
                
                {formSettings.emailNotifications && (
                  <div className="space-y-3 pl-6 border-l-2 border-gray-200">
                    <div>
                      <Label>Email Template</Label>
                      <Textarea
                        value={formSettings.emailTemplate}
                        onChange={(e) => setFormSettings(prev => ({ ...prev, emailTemplate: e.target.value }))}
                        placeholder="Email template for notifications..."
                      />
                    </div>
                    <div>
                      <Label>Recipients</Label>
                      <Input
                        placeholder="email1@example.com, email2@example.com"
                        onChange={(e) => setFormSettings(prev => ({ 
                          ...prev, 
                          recipients: e.target.value.split(',').map(email => email.trim()) 
                        }))}
                      />
                    </div>
                  </div>
                )}

                <div className="flex items-center space-x-2">
                  <Switch
                    checked={formSettings.requireAuth}
                    onCheckedChange={(checked) => setFormSettings(prev => ({ ...prev, requireAuth: checked }))}
                  />
                  <Label>Require authentication</Label>
                </div>

                <div className="flex items-center space-x-2">
                  <Switch
                    checked={formSettings.allowAnonymous}
                    onCheckedChange={(checked) => setFormSettings(prev => ({ ...prev, allowAnonymous: checked }))}
                  />
                  <Label>Allow anonymous submissions</Label>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        <TabsContent value="preview" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center justify-between">
                Live Preview
                <div className="flex items-center space-x-2">
                  <Button size="sm" variant="outline">
                    <Smartphone className="h-4 w-4 mr-2" />
                    Mobile
                  </Button>
                  <Button size="sm" variant="outline">
                    <Download className="h-4 w-4 mr-2" />
                    Export
                  </Button>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className={`border rounded-lg p-6 ${selectedDesign.preview}`}>
                <div className="bg-white rounded-lg p-6 shadow-lg max-w-2xl mx-auto">
                  <div className="space-y-4">
                    <div>
                      <h2 className="text-2xl font-bold text-gray-900">{formSettings.title}</h2>
                      {formSettings.description && (
                        <p className="text-gray-600 mt-2">{formSettings.description}</p>
                      )}
                    </div>
                    
                    {formFields.length === 0 ? (
                      <div className="text-center py-8 text-gray-500">
                        Add fields to see the form preview
                      </div>
                    ) : (
                      <div className="space-y-4">
                        {formFields.map((field) => (
                          <div key={field.id} className="space-y-2">
                            <Label className="text-sm font-medium">
                              {field.label}
                              {field.required && <span className="text-red-500 ml-1">*</span>}
                            </Label>
                            {field.type === "textarea" ? (
                              <Textarea placeholder={field.placeholder} />
                            ) : field.type === "select" ? (
                              <Select>
                                <SelectTrigger>
                                  <SelectValue placeholder={field.placeholder || "Select an option"} />
                                </SelectTrigger>
                                <SelectContent>
                                  {field.options?.map((option, index) => (
                                    <SelectItem key={index} value={option}>
                                      {option}
                                    </SelectItem>
                                  ))}
                                </SelectContent>
                              </Select>
                            ) : (
                              <Input 
                                type={field.type} 
                                placeholder={field.placeholder}
                              />
                            )}
                          </div>
                        ))}
                        <Button className="w-full mt-6">
                          Submit Form
                        </Button>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}