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 { 
  Palette, 
  Save, 
  Eye, 
  Plus, 
  Edit, 
  Trash2, 
  Download, 
  Upload,
  Gradient,
  Settings,
  Sparkles,
  Monitor,
  Smartphone,
  Tablet
} from "lucide-react";

interface Theme {
  id: number;
  name: string;
  displayName: string;
  description: string;
  isDefault: boolean;
  primaryColor: string;
  secondaryColor: string;
  accentColor: string;
  backgroundColor: string;
  gradientFrom?: string;
  gradientTo?: string;
  gradientDirection: string;
  fontFamily: string;
  borderRadius: string;
  formStyles: {
    inputStyle: 'modern' | 'classic' | 'minimal' | 'outlined' | 'filled';
    buttonStyle: 'rounded' | 'square' | 'pill' | 'ghost';
    cardStyle: 'elevated' | 'outlined' | 'flat' | 'glass';
    layout: 'vertical' | 'horizontal' | 'grid' | 'masonry';
  };
  animations: {
    enabled: boolean;
    duration: number;
    easing: string;
    hoverEffects: boolean;
    transitions: boolean;
  };
  isActive: boolean;
}

const predefinedThemes = [
  {
    name: "modern-blue",
    displayName: "Modern Blue",
    description: "Clean and professional with blue accents",
    primaryColor: "#3b82f6",
    secondaryColor: "#64748b",
    accentColor: "#10b981",
    backgroundColor: "#ffffff",
    gradientFrom: "#3b82f6",
    gradientTo: "#1d4ed8",
    formStyles: { inputStyle: 'modern', buttonStyle: 'rounded', cardStyle: 'elevated', layout: 'vertical' }
  },
  {
    name: "elegant-purple",
    displayName: "Elegant Purple",
    description: "Sophisticated purple gradient design",
    primaryColor: "#8b5cf6",
    secondaryColor: "#6b7280",
    accentColor: "#f59e0b",
    backgroundColor: "#fafafa",
    gradientFrom: "#8b5cf6",
    gradientTo: "#3b82f6",
    formStyles: { inputStyle: 'outlined', buttonStyle: 'pill', cardStyle: 'glass', layout: 'grid' }
  },
  {
    name: "nature-green",
    displayName: "Nature Green",
    description: "Fresh and natural green theme",
    primaryColor: "#10b981",
    secondaryColor: "#059669",
    accentColor: "#f59e0b",
    backgroundColor: "#f0fdf4",
    gradientFrom: "#10b981",
    gradientTo: "#059669",
    formStyles: { inputStyle: 'filled', buttonStyle: 'rounded', cardStyle: 'flat', layout: 'masonry' }
  }
];

export default function ThemeSettings() {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [selectedTheme, setSelectedTheme] = useState<Theme | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [previewMode, setPreviewMode] = useState<'desktop' | 'tablet' | 'mobile'>('desktop');

  // Fetch themes
  const { data: themes = [], isLoading } = useQuery({
    queryKey: ["/api/themes"],
    queryFn: async () => {
      const response = await fetch("/api/themes");
      if (!response.ok) throw new Error("Failed to fetch themes");
      return response.json();
    }
  });

  // Create theme mutation
  const createThemeMutation = useMutation({
    mutationFn: async (theme: Partial<Theme>) => {
      const response = await fetch("/api/themes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(theme)
      });
      if (!response.ok) throw new Error("Failed to create theme");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/themes"] });
      toast({ title: "Theme created successfully" });
      setIsEditing(false);
    }
  });

  // Update theme mutation
  const updateThemeMutation = useMutation({
    mutationFn: async ({ id, ...theme }: Partial<Theme> & { id: number }) => {
      const response = await fetch(`/api/themes/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(theme)
      });
      if (!response.ok) throw new Error("Failed to update theme");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/themes"] });
      toast({ title: "Theme updated successfully" });
      setIsEditing(false);
    }
  });

  // Delete theme mutation
  const deleteThemeMutation = useMutation({
    mutationFn: async (id: number) => {
      const response = await fetch(`/api/themes/${id}`, { method: "DELETE" });
      if (!response.ok) throw new Error("Failed to delete theme");
      return response.json();
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/themes"] });
      toast({ title: "Theme deleted successfully" });
      setSelectedTheme(null);
    }
  });

  const handleCreateTheme = () => {
    setSelectedTheme({
      id: 0,
      name: "",
      displayName: "",
      description: "",
      isDefault: false,
      primaryColor: "#3b82f6",
      secondaryColor: "#64748b",
      accentColor: "#10b981",
      backgroundColor: "#ffffff",
      gradientFrom: "#3b82f6",
      gradientTo: "#1d4ed8",
      gradientDirection: "to-r",
      fontFamily: "Inter",
      borderRadius: "8px",
      formStyles: {
        inputStyle: 'modern',
        buttonStyle: 'rounded',
        cardStyle: 'elevated',
        layout: 'vertical'
      },
      animations: {
        enabled: true,
        duration: 300,
        easing: "ease-in-out",
        hoverEffects: true,
        transitions: true
      },
      isActive: true
    });
    setIsEditing(true);
  };

  const handleSaveTheme = () => {
    if (!selectedTheme) return;
    
    if (selectedTheme.id === 0) {
      createThemeMutation.mutate(selectedTheme);
    } else {
      updateThemeMutation.mutate(selectedTheme);
    }
  };

  const handleInstallPredefinedTheme = (predefinedTheme: any) => {
    const newTheme = {
      ...predefinedTheme,
      gradientDirection: "to-r",
      fontFamily: "Inter",
      borderRadius: "8px",
      animations: {
        enabled: true,
        duration: 300,
        easing: "ease-in-out",
        hoverEffects: true,
        transitions: true
      },
      isActive: true,
      isDefault: false
    };
    createThemeMutation.mutate(newTheme);
  };

  const getPreviewWidth = () => {
    switch (previewMode) {
      case 'mobile': return 'max-w-sm';
      case 'tablet': return 'max-w-2xl';
      default: return 'max-w-4xl';
    }
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Theme Settings</h1>
          <p className="text-muted-foreground">
            Customize your application's appearance with beautiful themes and form designs
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <Badge variant="secondary" className="flex items-center space-x-1">
            <Sparkles className="h-3 w-3" />
            <span>18 Designs</span>
          </Badge>
          <Button onClick={handleCreateTheme} className="flex items-center space-x-2">
            <Plus className="h-4 w-4" />
            <span>Create Theme</span>
          </Button>
        </div>
      </div>

      <Tabs defaultValue="themes" className="w-full">
        <TabsList className="grid w-full grid-cols-3">
          <TabsTrigger value="themes">Themes</TabsTrigger>
          <TabsTrigger value="forms">Form Designs</TabsTrigger>
          <TabsTrigger value="preview">Live Preview</TabsTrigger>
        </TabsList>

        <TabsContent value="themes" className="space-y-6">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Theme List */}
            <Card>
              <CardHeader>
                <CardTitle>Your Themes</CardTitle>
                <CardDescription>Manage and customize your themes</CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                {isLoading ? (
                  <div className="text-center py-4">Loading themes...</div>
                ) : themes.length === 0 ? (
                  <div className="text-center py-4 text-muted-foreground">
                    No themes created yet
                  </div>
                ) : (
                  themes.map((theme: Theme) => (
                    <div
                      key={theme.id}
                      className={`p-4 border rounded-lg cursor-pointer transition-colors ${
                        selectedTheme?.id === theme.id
                          ? "border-primary bg-primary/5"
                          : "border-gray-200 hover:border-gray-300"
                      }`}
                      onClick={() => {
                        setSelectedTheme(theme);
                        setIsEditing(false);
                      }}
                    >
                      <div className="flex items-center justify-between">
                        <div className="flex-1">
                          <div className="flex items-center space-x-2 mb-1">
                            <h3 className="font-medium">{theme.displayName}</h3>
                            {theme.isDefault && (
                              <Badge variant="secondary" className="text-xs">Default</Badge>
                            )}
                            {!theme.isActive && (
                              <Badge variant="outline" className="text-xs">Inactive</Badge>
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">{theme.description}</p>
                          <div className="flex items-center space-x-1 mt-2">
                            <div 
                              className="w-4 h-4 rounded-full border border-gray-300"
                              style={{ backgroundColor: theme.primaryColor }}
                            />
                            <div 
                              className="w-4 h-4 rounded-full border border-gray-300"
                              style={{ backgroundColor: theme.secondaryColor }}
                            />
                            <div 
                              className="w-4 h-4 rounded-full border border-gray-300"
                              style={{ backgroundColor: theme.accentColor }}
                            />
                          </div>
                        </div>
                        <div className="flex items-center space-x-1">
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={(e) => {
                              e.stopPropagation();
                              setSelectedTheme(theme);
                              setIsEditing(true);
                            }}
                          >
                            <Edit className="h-3 w-3" />
                          </Button>
                          <Button
                            size="sm"
                            variant="ghost"
                            onClick={(e) => {
                              e.stopPropagation();
                              deleteThemeMutation.mutate(theme.id);
                            }}
                          >
                            <Trash2 className="h-3 w-3" />
                          </Button>
                        </div>
                      </div>
                    </div>
                  ))
                )}
              </CardContent>
            </Card>

            {/* Theme Editor */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Palette className="h-5 w-5" />
                  <span>{isEditing ? 'Edit Theme' : 'Theme Details'}</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {!selectedTheme ? (
                  <div className="text-center py-8 text-muted-foreground">
                    Select a theme to view details or create a new one
                  </div>
                ) : (
                  <div className="space-y-4">
                    {isEditing ? (
                      <>
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <Label>Name</Label>
                            <Input
                              value={selectedTheme.name}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, name: e.target.value} : null)}
                              placeholder="theme-name"
                            />
                          </div>
                          <div>
                            <Label>Display Name</Label>
                            <Input
                              value={selectedTheme.displayName}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, displayName: e.target.value} : null)}
                              placeholder="Theme Name"
                            />
                          </div>
                        </div>

                        <div>
                          <Label>Description</Label>
                          <Textarea
                            value={selectedTheme.description}
                            onChange={(e) => setSelectedTheme(prev => prev ? {...prev, description: e.target.value} : null)}
                            placeholder="Theme description"
                          />
                        </div>

                        <div className="grid grid-cols-3 gap-4">
                          <div>
                            <Label>Primary Color</Label>
                            <Input
                              type="color"
                              value={selectedTheme.primaryColor}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, primaryColor: e.target.value} : null)}
                            />
                          </div>
                          <div>
                            <Label>Secondary Color</Label>
                            <Input
                              type="color"
                              value={selectedTheme.secondaryColor}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, secondaryColor: e.target.value} : null)}
                            />
                          </div>
                          <div>
                            <Label>Accent Color</Label>
                            <Input
                              type="color"
                              value={selectedTheme.accentColor}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, accentColor: e.target.value} : null)}
                            />
                          </div>
                        </div>

                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <Label>Gradient From</Label>
                            <Input
                              type="color"
                              value={selectedTheme.gradientFrom || selectedTheme.primaryColor}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, gradientFrom: e.target.value} : null)}
                            />
                          </div>
                          <div>
                            <Label>Gradient To</Label>
                            <Input
                              type="color"
                              value={selectedTheme.gradientTo || selectedTheme.secondaryColor}
                              onChange={(e) => setSelectedTheme(prev => prev ? {...prev, gradientTo: e.target.value} : null)}
                            />
                          </div>
                        </div>

                        <div className="flex items-center space-x-4">
                          <div className="flex items-center space-x-2">
                            <Switch
                              checked={selectedTheme.isDefault}
                              onCheckedChange={(checked) => setSelectedTheme(prev => prev ? {...prev, isDefault: checked} : null)}
                            />
                            <Label>Set as Default</Label>
                          </div>
                          <div className="flex items-center space-x-2">
                            <Switch
                              checked={selectedTheme.isActive}
                              onCheckedChange={(checked) => setSelectedTheme(prev => prev ? {...prev, isActive: checked} : null)}
                            />
                            <Label>Active</Label>
                          </div>
                        </div>

                        <div className="flex items-center space-x-2 pt-4">
                          <Button onClick={handleSaveTheme} className="flex items-center space-x-2">
                            <Save className="h-4 w-4" />
                            <span>Save Theme</span>
                          </Button>
                          <Button 
                            variant="outline" 
                            onClick={() => setIsEditing(false)}
                          >
                            Cancel
                          </Button>
                        </div>
                      </>
                    ) : (
                      <>
                        <div className="space-y-3">
                          <div>
                            <h3 className="font-medium">{selectedTheme.displayName}</h3>
                            <p className="text-sm text-muted-foreground">{selectedTheme.description}</p>
                          </div>
                          
                          <div className="flex items-center space-x-2">
                            <span className="text-sm font-medium">Colors:</span>
                            <div className="flex items-center space-x-1">
                              <div 
                                className="w-6 h-6 rounded border border-gray-300"
                                style={{ backgroundColor: selectedTheme.primaryColor }}
                                title="Primary"
                              />
                              <div 
                                className="w-6 h-6 rounded border border-gray-300"
                                style={{ backgroundColor: selectedTheme.secondaryColor }}
                                title="Secondary"
                              />
                              <div 
                                className="w-6 h-6 rounded border border-gray-300"
                                style={{ backgroundColor: selectedTheme.accentColor }}
                                title="Accent"
                              />
                            </div>
                          </div>
                        </div>

                        <div className="flex items-center space-x-2 pt-4">
                          <Button 
                            onClick={() => setIsEditing(true)}
                            className="flex items-center space-x-2"
                          >
                            <Edit className="h-4 w-4" />
                            <span>Edit Theme</span>
                          </Button>
                          <Button 
                            variant="outline"
                            onClick={() => {/* Apply theme logic */}}
                            className="flex items-center space-x-2"
                          >
                            <Eye className="h-4 w-4" />
                            <span>Preview</span>
                          </Button>
                        </div>
                      </>
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {/* Predefined Themes */}
          <Card>
            <CardHeader>
              <CardTitle>Predefined Themes</CardTitle>
              <CardDescription>
                Install beautiful pre-designed themes to get started quickly
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {predefinedThemes.map((theme, index) => (
                  <div key={index} className="border rounded-lg p-4 hover:border-primary transition-colors">
                    <div className="space-y-3">
                      <div>
                        <h3 className="font-medium">{theme.displayName}</h3>
                        <p className="text-sm text-muted-foreground">{theme.description}</p>
                      </div>
                      
                      <div className="flex items-center space-x-1">
                        <div 
                          className="w-4 h-4 rounded-full border border-gray-300"
                          style={{ backgroundColor: theme.primaryColor }}
                        />
                        <div 
                          className="w-4 h-4 rounded-full border border-gray-300"
                          style={{ backgroundColor: theme.secondaryColor }}
                        />
                        <div 
                          className="w-4 h-4 rounded-full border border-gray-300"
                          style={{ backgroundColor: theme.accentColor }}
                        />
                      </div>

                      <Button 
                        size="sm" 
                        variant="outline" 
                        className="w-full"
                        onClick={() => handleInstallPredefinedTheme(theme)}
                      >
                        <Download className="h-3 w-3 mr-2" />
                        Install Theme
                      </Button>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="forms" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Form Design Templates</CardTitle>
              <CardDescription>18 beautiful form designs for different use cases</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="text-center py-8 text-muted-foreground">
                Form design templates will be implemented here
              </div>
            </CardContent>
          </Card>
        </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={previewMode === 'desktop' ? 'default' : 'outline'}
                    onClick={() => setPreviewMode('desktop')}
                  >
                    <Monitor className="h-4 w-4" />
                  </Button>
                  <Button
                    size="sm"
                    variant={previewMode === 'tablet' ? 'default' : 'outline'}
                    onClick={() => setPreviewMode('tablet')}
                  >
                    <Tablet className="h-4 w-4" />
                  </Button>
                  <Button
                    size="sm"
                    variant={previewMode === 'mobile' ? 'default' : 'outline'}
                    onClick={() => setPreviewMode('mobile')}
                  >
                    <Smartphone className="h-4 w-4" />
                  </Button>
                </div>
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className={`mx-auto border rounded-lg p-6 ${getPreviewWidth()}`}>
                <div className="text-center py-8 text-muted-foreground">
                  Live theme preview will be shown here
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}