import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { useToast } from "@/hooks/use-toast";
import { Palette, Upload, Globe, Code, Facebook, Twitter, Instagram, Linkedin, Youtube, Save } from "lucide-react";
import { apiRequest, queryClient } from "@/lib/queryClient";
import type { BrandingSettings } from "@shared/schema";

export default function BrandingSettingsPage() {
  const { toast } = useToast();
  const [logoPreview, setLogoPreview] = useState<string>("");
  const [faviconPreview, setFaviconPreview] = useState<string>("");

  const { data: settings, isLoading } = useQuery<BrandingSettings>({
    queryKey: ["/api/branding-settings"],
  });

  const [formData, setFormData] = useState({
    primaryColor: settings?.primaryColor || "#3b82f6",
    secondaryColor: settings?.secondaryColor || "#64748b",
    accentColor: settings?.accentColor || "#10b981",
    logoUrl: settings?.logoUrl || "",
    faviconUrl: settings?.faviconUrl || "",
    websiteUrl: settings?.websiteUrl || "",
    customCss: settings?.customCss || "",
    customJs: settings?.customJs || "",
    facebook: settings?.socialMedia?.facebook || "",
    twitter: settings?.socialMedia?.twitter || "",
    instagram: settings?.socialMedia?.instagram || "",
    linkedin: settings?.socialMedia?.linkedin || "",
    youtube: settings?.socialMedia?.youtube || "",
    metaTitle: settings?.seoSettings?.metaTitle || "",
    metaDescription: settings?.seoSettings?.metaDescription || "",
    metaKeywords: settings?.seoSettings?.metaKeywords || "",
    ogImage: settings?.seoSettings?.ogImage || "",
  });

  const updateMutation = useMutation({
    mutationFn: async (data: any) => {
      const response = await apiRequest("branding-settings", "POST", {
        primaryColor: data.primaryColor,
        secondaryColor: data.secondaryColor,
        accentColor: data.accentColor,
        logoUrl: data.logoUrl,
        faviconUrl: data.faviconUrl,
        websiteUrl: data.websiteUrl,
        customCss: data.customCss,
        customJs: data.customJs,
        socialMedia: {
          facebook: data.facebook,
          twitter: data.twitter,
          instagram: data.instagram,
          linkedin: data.linkedin,
          youtube: data.youtube,
        },
        seoSettings: {
          metaTitle: data.metaTitle,
          metaDescription: data.metaDescription,
          metaKeywords: data.metaKeywords,
          ogImage: data.ogImage,
        },
      });
      return response;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/branding-settings"] });
      toast({
        title: "Success",
        description: "Branding settings updated successfully",
      });
    },
    onError: () => {
      toast({
        title: "Error",
        description: "Failed to update branding settings",
        variant: "destructive",
      });
    },
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    updateMutation.mutate(formData);
  };

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

  if (isLoading) {
    return (
      <div className="container mx-auto px-4 py-6">
        <div className="animate-pulse space-y-4">
          <div className="h-8 bg-gray-200 rounded w-1/3"></div>
          <div className="h-64 bg-gray-200 rounded"></div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 sm:px-6 lg:px-8 py-6">
      <div className="mb-6">
        <h1 className="text-3xl font-bold text-gray-900">Branding Settings</h1>
        <p className="text-gray-600 mt-2">Customize your organization's brand identity and appearance</p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Colors Section */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Palette className="h-5 w-5" />
              Brand Colors
            </CardTitle>
            <CardDescription>Define your organization's color palette</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="space-y-2">
                <Label htmlFor="primaryColor">Primary Color</Label>
                <div className="flex gap-2 items-center">
                  <Input
                    id="primaryColor"
                    type="color"
                    value={formData.primaryColor}
                    onChange={(e) => handleChange("primaryColor", e.target.value)}
                    className="w-20 h-10"
                    data-testid="input-primary-color"
                  />
                  <Input
                    type="text"
                    value={formData.primaryColor}
                    onChange={(e) => handleChange("primaryColor", e.target.value)}
                    className="flex-1"
                    placeholder="#3b82f6"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="secondaryColor">Secondary Color</Label>
                <div className="flex gap-2 items-center">
                  <Input
                    id="secondaryColor"
                    type="color"
                    value={formData.secondaryColor}
                    onChange={(e) => handleChange("secondaryColor", e.target.value)}
                    className="w-20 h-10"
                    data-testid="input-secondary-color"
                  />
                  <Input
                    type="text"
                    value={formData.secondaryColor}
                    onChange={(e) => handleChange("secondaryColor", e.target.value)}
                    className="flex-1"
                    placeholder="#64748b"
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="accentColor">Accent Color</Label>
                <div className="flex gap-2 items-center">
                  <Input
                    id="accentColor"
                    type="color"
                    value={formData.accentColor}
                    onChange={(e) => handleChange("accentColor", e.target.value)}
                    className="w-20 h-10"
                    data-testid="input-accent-color"
                  />
                  <Input
                    type="text"
                    value={formData.accentColor}
                    onChange={(e) => handleChange("accentColor", e.target.value)}
                    className="flex-1"
                    placeholder="#10b981"
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Logos Section */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Upload className="h-5 w-5" />
              Logos & Icons
            </CardTitle>
            <CardDescription>Upload your organization's branding assets</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="logoUrl">Logo URL</Label>
                <Input
                  id="logoUrl"
                  type="url"
                  value={formData.logoUrl}
                  onChange={(e) => handleChange("logoUrl", e.target.value)}
                  placeholder="https://example.com/logo.png"
                  data-testid="input-logo-url"
                />
                {formData.logoUrl && (
                  <img src={formData.logoUrl} alt="Logo Preview" className="mt-2 h-16 object-contain" />
                )}
              </div>
              <div className="space-y-2">
                <Label htmlFor="faviconUrl">Favicon URL</Label>
                <Input
                  id="faviconUrl"
                  type="url"
                  value={formData.faviconUrl}
                  onChange={(e) => handleChange("faviconUrl", e.target.value)}
                  placeholder="https://example.com/favicon.ico"
                  data-testid="input-favicon-url"
                />
                {formData.faviconUrl && (
                  <img src={formData.faviconUrl} alt="Favicon Preview" className="mt-2 h-8 object-contain" />
                )}
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Website Integration */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Globe className="h-5 w-5" />
              Website Integration
            </CardTitle>
            <CardDescription>Configure your organization's web presence</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="websiteUrl">Website URL</Label>
              <Input
                id="websiteUrl"
                type="url"
                value={formData.websiteUrl}
                onChange={(e) => handleChange("websiteUrl", e.target.value)}
                placeholder="https://www.yourorganization.com"
                data-testid="input-website-url"
              />
            </div>
          </CardContent>
        </Card>

        {/* Social Media */}
        <Card>
          <CardHeader>
            <CardTitle>Social Media Links</CardTitle>
            <CardDescription>Connect your social media profiles</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="facebook" className="flex items-center gap-2">
                  <Facebook className="h-4 w-4" />
                  Facebook
                </Label>
                <Input
                  id="facebook"
                  type="url"
                  value={formData.facebook}
                  onChange={(e) => handleChange("facebook", e.target.value)}
                  placeholder="https://facebook.com/yourpage"
                  data-testid="input-facebook"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="twitter" className="flex items-center gap-2">
                  <Twitter className="h-4 w-4" />
                  Twitter
                </Label>
                <Input
                  id="twitter"
                  type="url"
                  value={formData.twitter}
                  onChange={(e) => handleChange("twitter", e.target.value)}
                  placeholder="https://twitter.com/yourhandle"
                  data-testid="input-twitter"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="instagram" className="flex items-center gap-2">
                  <Instagram className="h-4 w-4" />
                  Instagram
                </Label>
                <Input
                  id="instagram"
                  type="url"
                  value={formData.instagram}
                  onChange={(e) => handleChange("instagram", e.target.value)}
                  placeholder="https://instagram.com/yourprofile"
                  data-testid="input-instagram"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="linkedin" className="flex items-center gap-2">
                  <Linkedin className="h-4 w-4" />
                  LinkedIn
                </Label>
                <Input
                  id="linkedin"
                  type="url"
                  value={formData.linkedin}
                  onChange={(e) => handleChange("linkedin", e.target.value)}
                  placeholder="https://linkedin.com/company/yourcompany"
                  data-testid="input-linkedin"
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="youtube" className="flex items-center gap-2">
                  <Youtube className="h-4 w-4" />
                  YouTube
                </Label>
                <Input
                  id="youtube"
                  type="url"
                  value={formData.youtube}
                  onChange={(e) => handleChange("youtube", e.target.value)}
                  placeholder="https://youtube.com/channel/yourchannel"
                  data-testid="input-youtube"
                />
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Custom Code */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Code className="h-5 w-5" />
              Custom Code
            </CardTitle>
            <CardDescription>Add custom CSS and JavaScript for advanced customization</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="customCss">Custom CSS</Label>
              <Textarea
                id="customCss"
                value={formData.customCss}
                onChange={(e) => handleChange("customCss", e.target.value)}
                placeholder=".custom-class { color: red; }"
                rows={6}
                className="font-mono text-sm"
                data-testid="input-custom-css"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="customJs">Custom JavaScript</Label>
              <Textarea
                id="customJs"
                value={formData.customJs}
                onChange={(e) => handleChange("customJs", e.target.value)}
                placeholder="console.log('Custom JS');"
                rows={6}
                className="font-mono text-sm"
                data-testid="input-custom-js"
              />
            </div>
          </CardContent>
        </Card>

        {/* SEO Settings */}
        <Card>
          <CardHeader>
            <CardTitle>SEO Settings</CardTitle>
            <CardDescription>Optimize your organization's search engine presence</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="metaTitle">Meta Title</Label>
              <Input
                id="metaTitle"
                type="text"
                value={formData.metaTitle}
                onChange={(e) => handleChange("metaTitle", e.target.value)}
                placeholder="Your Organization Name - Sports Management"
                data-testid="input-meta-title"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="metaDescription">Meta Description</Label>
              <Textarea
                id="metaDescription"
                value={formData.metaDescription}
                onChange={(e) => handleChange("metaDescription", e.target.value)}
                placeholder="Brief description of your organization for search engines"
                rows={3}
                data-testid="input-meta-description"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="metaKeywords">Meta Keywords</Label>
              <Input
                id="metaKeywords"
                type="text"
                value={formData.metaKeywords}
                onChange={(e) => handleChange("metaKeywords", e.target.value)}
                placeholder="sports, team, management, organization"
                data-testid="input-meta-keywords"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="ogImage">Open Graph Image URL</Label>
              <Input
                id="ogImage"
                type="url"
                value={formData.ogImage}
                onChange={(e) => handleChange("ogImage", e.target.value)}
                placeholder="https://example.com/og-image.jpg"
                data-testid="input-og-image"
              />
              {formData.ogImage && (
                <img src={formData.ogImage} alt="OG Image Preview" className="mt-2 h-32 object-contain" />
              )}
            </div>
          </CardContent>
        </Card>

        <div className="flex justify-end">
          <Button 
            type="submit" 
            size="lg" 
            disabled={updateMutation.isPending}
            className="flex items-center gap-2"
            data-testid="button-save-branding"
          >
            <Save className="h-4 w-4" />
            {updateMutation.isPending ? "Saving..." : "Save Changes"}
          </Button>
        </div>
      </form>
    </div>
  );
}
