'use client';

import { useState, useEffect } 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 { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Plus, Edit, Trash2, Eye, EyeOff } from 'lucide-react';
import ImageUpload from '@/components/ImageUpload';
import { Slider, SliderSlide } from '@/lib/data-store';

export default function SliderManagePage() {
  const [sliders, setSliders] = useState<Slider[]>([]);
  const [loading, setLoading] = useState(true);
  const [editingSlider, setEditingSlider] = useState<Slider | null>(null);
  const [editingSlide, setEditingSlide] = useState<SliderSlide | null>(null);
  const [showSlideForm, setShowSlideForm] = useState(false);
  
  const [sliderFormData, setSliderFormData] = useState({
    name: '',
    type: 'hero' as 'hero' | 'product' | 'testimonial' | 'gallery',
    settings: {
      autoPlay: true,
      autoPlayDelay: 5000,
      showDots: true,
      showArrows: true,
      infinite: true,
      slidesToShow: 1,
      slidesToScroll: 1
    },
    isActive: true
  });

  const [slideFormData, setSlideFormData] = useState({
    title: '',
    subtitle: '',
    description: '',
    image: '',
    buttonText: '',
    buttonLink: '',
    buttonStyle: 'primary' as 'primary' | 'secondary' | 'outline',
    textPosition: 'center' as 'left' | 'center' | 'right',
    isActive: true,
    order: 1
  });

  useEffect(() => {
    fetchSliders();
  }, []);

  const fetchSliders = async () => {
    try {
      const response = await fetch('/api/admin/sliders');
      if (response.ok) {
        const data = await response.json();
        setSliders(data);
      }
    } catch (error) {
      console.error('Error fetching sliders:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleSliderSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      if (editingSlider) {
        const response = await fetch(`/api/admin/sliders/${editingSlider.id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(sliderFormData)
        });
        
        if (response.ok) {
          fetchSliders();
          resetSliderForm();
        }
      } else {
        const response = await fetch('/api/admin/sliders', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ ...sliderFormData, slides: [] })
        });
        
        if (response.ok) {
          fetchSliders();
          resetSliderForm();
        }
      }
    } catch (error) {
      console.error('Error saving slider:', error);
    }
  };

  const handleSlideSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!editingSlider) return;

    try {
      const updatedSlides = editingSlide 
        ? editingSlider.slides.map(slide => 
            slide.id === editingSlide.id 
              ? { ...slide, ...slideFormData, updatedAt: new Date().toISOString() }
              : slide
          )
        : [...editingSlider.slides, {
            ...slideFormData,
            id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString()
          }];

      const response = await fetch(`/api/admin/sliders/${editingSlider.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...editingSlider, slides: updatedSlides })
      });
      
      if (response.ok) {
        fetchSliders();
        resetSlideForm();
        setShowSlideForm(false);
      }
    } catch (error) {
      console.error('Error saving slide:', error);
    }
  };

  const handleDeleteSlider = async (id: string) => {
    if (confirm('Are you sure you want to delete this slider?')) {
      try {
        const response = await fetch(`/api/admin/sliders/${id}`, {
          method: 'DELETE'
        });
        
        if (response.ok) {
          fetchSliders();
        }
      } catch (error) {
        console.error('Error deleting slider:', error);
      }
    }
  };

  const handleDeleteSlide = async (slideId: string) => {
    if (!editingSlider || !confirm('Are you sure you want to delete this slide?')) return;

    try {
      const updatedSlides = editingSlider.slides.filter(slide => slide.id !== slideId);

      const response = await fetch(`/api/admin/sliders/${editingSlider.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...editingSlider, slides: updatedSlides })
      });
      
      if (response.ok) {
        fetchSliders();
        // Update local editing slider
        const updated = sliders.find(s => s.id === editingSlider.id);
        if (updated) setEditingSlider(updated);
      }
    } catch (error) {
      console.error('Error deleting slide:', error);
    }
  };

  const resetSliderForm = () => {
    setSliderFormData({
      name: '',
      type: 'hero',
      settings: {
        autoPlay: true,
        autoPlayDelay: 5000,
        showDots: true,
        showArrows: true,
        infinite: true,
        slidesToShow: 1,
        slidesToScroll: 1
      },
      isActive: true
    });
    setEditingSlider(null);
  };

  const resetSlideForm = () => {
    setSlideFormData({
      title: '',
      subtitle: '',
      description: '',
      image: '',
      buttonText: '',
      buttonLink: '',
      buttonStyle: 'primary',
      textPosition: 'center',
      isActive: true,
      order: 1
    });
    setEditingSlide(null);
  };

  const editSlider = (slider: Slider) => {
    setSliderFormData({
      name: slider.name,
      type: slider.type,
      settings: slider.settings,
      isActive: slider.isActive
    });
    setEditingSlider(slider);
  };

  const editSlide = (slide: SliderSlide) => {
    setSlideFormData({
      title: slide.title,
      subtitle: slide.subtitle || '',
      description: slide.description || '',
      image: slide.image,
      buttonText: slide.buttonText || '',
      buttonLink: slide.buttonLink || '',
      buttonStyle: slide.buttonStyle || 'primary',
      textPosition: slide.textPosition || 'center',
      isActive: slide.isActive,
      order: slide.order
    });
    setEditingSlide(slide);
    setShowSlideForm(true);
  };

  if (loading) {
    return <div className="flex justify-center items-center h-64">Loading...</div>;
  }

  return (
    <div className="max-w-7xl mx-auto p-6">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900">Slider Management</h1>
        <p className="text-gray-600 mt-2">Manage website sliders and their content</p>
      </div>

      <Tabs defaultValue="sliders" className="w-full">
        <TabsList>
          <TabsTrigger value="sliders">Sliders</TabsTrigger>
          {editingSlider && <TabsTrigger value="slides">Manage Slides</TabsTrigger>}
        </TabsList>

        {/* Sliders Tab */}
        <TabsContent value="sliders" className="space-y-6">
          {/* Slider Form */}
          <Card>
            <CardHeader>
              <CardTitle>{editingSlider ? 'Edit Slider' : 'Create New Slider'}</CardTitle>
              <CardDescription>
                Configure slider settings and properties
              </CardDescription>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSliderSubmit} className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label htmlFor="sliderName">Slider Name</Label>
                    <Input
                      id="sliderName"
                      value={sliderFormData.name}
                      onChange={(e) => setSliderFormData({ ...sliderFormData, name: e.target.value })}
                      placeholder="e.g., Hero Banner Slider"
                      required
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="sliderType">Slider Type</Label>
                    <Select 
                      value={sliderFormData.type}
                      onValueChange={(value: 'hero' | 'product' | 'testimonial' | 'gallery') => 
                        setSliderFormData({ ...sliderFormData, type: value })
                      }
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="hero">Hero Banner</SelectItem>
                        <SelectItem value="product">Product Gallery</SelectItem>
                        <SelectItem value="testimonial">Testimonials</SelectItem>
                        <SelectItem value="gallery">Image Gallery</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div>
                    <Label htmlFor="autoPlayDelay">Auto-play Delay (ms)</Label>
                    <Input
                      id="autoPlayDelay"
                      type="number"
                      value={sliderFormData.settings.autoPlayDelay}
                      onChange={(e) => setSliderFormData({ 
                        ...sliderFormData, 
                        settings: { 
                          ...sliderFormData.settings, 
                          autoPlayDelay: parseInt(e.target.value) || 5000 
                        }
                      })}
                    />
                  </div>
                  
                  <div className="flex items-center space-x-4 pt-6">
                    <label className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={sliderFormData.settings.autoPlay}
                        onChange={(e) => setSliderFormData({ 
                          ...sliderFormData, 
                          settings: { ...sliderFormData.settings, autoPlay: e.target.checked }
                        })}
                      />
                      <span>Auto-play</span>
                    </label>
                    
                    <label className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={sliderFormData.settings.showArrows}
                        onChange={(e) => setSliderFormData({ 
                          ...sliderFormData, 
                          settings: { ...sliderFormData.settings, showArrows: e.target.checked }
                        })}
                      />
                      <span>Show Arrows</span>
                    </label>
                  </div>
                  
                  <div className="flex items-center space-x-4 pt-6">
                    <label className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={sliderFormData.settings.showDots}
                        onChange={(e) => setSliderFormData({ 
                          ...sliderFormData, 
                          settings: { ...sliderFormData.settings, showDots: e.target.checked }
                        })}
                      />
                      <span>Show Dots</span>
                    </label>
                    
                    <label className="flex items-center space-x-2">
                      <input
                        type="checkbox"
                        checked={sliderFormData.isActive}
                        onChange={(e) => setSliderFormData({ ...sliderFormData, isActive: e.target.checked })}
                      />
                      <span>Active</span>
                    </label>
                  </div>
                </div>

                <div className="flex gap-2">
                  <Button type="submit">
                    {editingSlider ? 'Update Slider' : 'Create Slider'}
                  </Button>
                  {editingSlider && (
                    <Button type="button" variant="outline" onClick={resetSliderForm}>
                      Cancel
                    </Button>
                  )}
                </div>
              </form>
            </CardContent>
          </Card>

          {/* Sliders List */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {sliders.map((slider) => (
              <Card key={slider.id}>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-lg">{slider.name}</CardTitle>
                    <div className="flex items-center gap-2">
                      <Badge variant={slider.isActive ? 'default' : 'secondary'}>
                        {slider.isActive ? 'Active' : 'Inactive'}
                      </Badge>
                      <Badge variant="outline">{slider.type}</Badge>
                    </div>
                  </div>
                  <CardDescription>
                    {slider.slides.length} slide{slider.slides.length !== 1 ? 's' : ''}
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="flex gap-2">
                    <Button size="sm" onClick={() => editSlider(slider)}>
                      <Edit className="h-4 w-4" />
                    </Button>
                    <Button 
                      size="sm" 
                      variant="outline"
                      onClick={() => {
                        setEditingSlider(slider);
                        // Switch to slides tab
                        const slidesTab = document.querySelector('[value="slides"]') as HTMLElement;
                        if (slidesTab) slidesTab.click();
                      }}
                    >
                      Manage Slides
                    </Button>
                    <Button 
                      size="sm" 
                      variant="destructive"
                      onClick={() => handleDeleteSlider(slider.id)}
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* Slides Tab */}
        {editingSlider && (
          <TabsContent value="slides" className="space-y-6">
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>Slides for: {editingSlider.name}</CardTitle>
                    <CardDescription>
                      Manage individual slides within this slider
                    </CardDescription>
                  </div>
                  <Button onClick={() => setShowSlideForm(true)}>
                    <Plus className="h-4 w-4 mr-2" />
                    Add Slide
                  </Button>
                </div>
              </CardHeader>
              
              {showSlideForm && (
                <CardContent className="border-t">
                  <form onSubmit={handleSlideSubmit} className="space-y-4 mt-4">
                    <h3 className="text-lg font-semibold">
                      {editingSlide ? 'Edit Slide' : 'Add New Slide'}
                    </h3>
                    
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor="slideTitle">Title</Label>
                        <Input
                          id="slideTitle"
                          value={slideFormData.title}
                          onChange={(e) => setSlideFormData({ ...slideFormData, title: e.target.value })}
                          required
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="slideSubtitle">Subtitle</Label>
                        <Input
                          id="slideSubtitle"
                          value={slideFormData.subtitle}
                          onChange={(e) => setSlideFormData({ ...slideFormData, subtitle: e.target.value })}
                        />
                      </div>
                    </div>

                    <div>
                      <Label htmlFor="slideDescription">Description</Label>
                      <Textarea
                        id="slideDescription"
                        value={slideFormData.description}
                        onChange={(e) => setSlideFormData({ ...slideFormData, description: e.target.value })}
                      />
                    </div>

                    <div>
                      <ImageUpload
                        label="Background Image"
                        currentImage={slideFormData.image}
                        onImageUploaded={(url) => setSlideFormData({ ...slideFormData, image: url })}
                        accept="image/*"
                      />
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div>
                        <Label htmlFor="buttonText">Button Text</Label>
                        <Input
                          id="buttonText"
                          value={slideFormData.buttonText}
                          onChange={(e) => setSlideFormData({ ...slideFormData, buttonText: e.target.value })}
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="buttonLink">Button Link</Label>
                        <Input
                          id="buttonLink"
                          value={slideFormData.buttonLink}
                          onChange={(e) => setSlideFormData({ ...slideFormData, buttonLink: e.target.value })}
                        />
                      </div>
                      
                      <div>
                        <Label htmlFor="buttonStyle">Button Style</Label>
                        <Select 
                          value={slideFormData.buttonStyle}
                          onValueChange={(value: 'primary' | 'secondary' | 'outline') => 
                            setSlideFormData({ ...slideFormData, buttonStyle: value })
                          }
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="primary">Primary</SelectItem>
                            <SelectItem value="secondary">Secondary</SelectItem>
                            <SelectItem value="outline">Outline</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>

                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                      <div>
                        <Label htmlFor="textPosition">Text Position</Label>
                        <Select 
                          value={slideFormData.textPosition}
                          onValueChange={(value: 'left' | 'center' | 'right') => 
                            setSlideFormData({ ...slideFormData, textPosition: value })
                          }
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="left">Left</SelectItem>
                            <SelectItem value="center">Center</SelectItem>
                            <SelectItem value="right">Right</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      
                      <div>
                        <Label htmlFor="slideOrder">Order</Label>
                        <Input
                          id="slideOrder"
                          type="number"
                          value={slideFormData.order}
                          onChange={(e) => setSlideFormData({ ...slideFormData, order: parseInt(e.target.value) || 1 })}
                        />
                      </div>
                      
                      <div className="flex items-center space-x-2 pt-6">
                        <input
                          type="checkbox"
                          checked={slideFormData.isActive}
                          onChange={(e) => setSlideFormData({ ...slideFormData, isActive: e.target.checked })}
                        />
                        <Label>Active</Label>
                      </div>
                    </div>

                    <div className="flex gap-2">
                      <Button type="submit">
                        {editingSlide ? 'Update Slide' : 'Add Slide'}
                      </Button>
                      <Button 
                        type="button" 
                        variant="outline" 
                        onClick={() => {
                          resetSlideForm();
                          setShowSlideForm(false);
                        }}
                      >
                        Cancel
                      </Button>
                    </div>
                  </form>
                </CardContent>
              )}
            </Card>

            {/* Slides List */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              {editingSlider.slides
                .sort((a, b) => a.order - b.order)
                .map((slide) => (
                <Card key={slide.id}>
                  <CardHeader>
                    <div className="flex items-center justify-between">
                      <CardTitle className="text-lg">{slide.title}</CardTitle>
                      <div className="flex items-center gap-1">
                        {slide.isActive ? 
                          <Eye className="h-4 w-4 text-green-600" /> : 
                          <EyeOff className="h-4 w-4 text-gray-400" />
                        }
                        <Badge variant="outline">#{slide.order}</Badge>
                      </div>
                    </div>
                    {slide.subtitle && (
                      <CardDescription>{slide.subtitle}</CardDescription>
                    )}
                  </CardHeader>
                  <CardContent>
                    {slide.image && (
                      <div className="relative h-32 bg-gray-100 rounded mb-3 overflow-hidden">
                        <img 
                          src={slide.image} 
                          alt={slide.title}
                          className="w-full h-full object-cover"
                        />
                      </div>
                    )}
                    <div className="flex gap-2">
                      <Button size="sm" onClick={() => editSlide(slide)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                      <Button 
                        size="sm" 
                        variant="destructive"
                        onClick={() => handleDeleteSlide(slide.id)}
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </TabsContent>
        )}
      </Tabs>
    </div>
  );
}