import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Plus, Edit, Trash2, Save, X, LogOut, Image as ImageIcon, 
  MapPin, DollarSign, Star, Tag, Calendar, Home
} from 'lucide-react';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { Textarea } from '../components/ui/textarea';
import { Card, CardContent, CardHeader, CardTitle } from '../components/ui/card';
import { Badge } from '../components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../components/ui/tabs';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '../components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../components/ui/select';
import { toast } from 'sonner';
import { destinationsAPI, specialsAPI, uploadAPI } from '../services/api';

const AdminDashboard = () => {
  const navigate = useNavigate();
  const [destinations, setDestinations] = useState([]);
  const [specials, setSpecials] = useState([]);
  const [loading, setLoading] = useState(true);
  const [isEditMode, setIsEditMode] = useState(false);
  const [editingDestination, setEditingDestination] = useState(null);
  const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
  const [newDestination, setNewDestination] = useState({
    name: '',
    location: '',
    description: '',
    image: '',
    category: 'City',
    rating: 4.5,
    price: 999,
    currency: 'USD'
  });

  useEffect(() => {
    const isAuthenticated = localStorage.getItem('isAdminAuthenticated');
    if (!isAuthenticated) {
      navigate('/admin');
    } else {
      fetchData();
    }
  }, [navigate]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const [destinationsData, specialsData] = await Promise.all([
        destinationsAPI.getAll(),
        specialsAPI.getAll()
      ]);
      setDestinations(destinationsData);
      setSpecials(specialsData);
    } catch (error) {
      console.error('Error fetching data:', error);
      toast.error('Failed to load data');
    } finally {
      setLoading(false);
    }
  };

  const handleLogout = () => {
    localStorage.removeItem('isAdminAuthenticated');
    localStorage.removeItem('auth_token');
    toast.success('Logged out successfully');
    navigate('/admin');
  };

  const handleAddDestination = async () => {
    try {
      const newDest = await destinationsAPI.create({
        ...newDestination,
        rating: parseFloat(newDestination.rating),
        price: parseFloat(newDestination.price)
      });
      setDestinations([...destinations, newDest]);
      setIsAddDialogOpen(false);
      setNewDestination({
        name: '',
        location: '',
        description: '',
        image: '',
        category: 'City',
        rating: 4.5,
        price: 999,
        currency: 'USD'
      });
      toast.success('Destination added successfully!');
    } catch (error) {
      console.error('Error adding destination:', error);
      toast.error('Failed to add destination');
    }
  };

  const handleEditDestination = (destination) => {
    setEditingDestination({ ...destination });
    setIsEditMode(true);
  };

  const handleSaveEdit = async () => {
    try {
      const updated = await destinationsAPI.update(editingDestination.id, editingDestination);
      setDestinations(destinations.map(dest =>
        dest.id === updated.id ? updated : dest
      ));
      setIsEditMode(false);
      setEditingDestination(null);
      toast.success('Destination updated successfully!');
    } catch (error) {
      console.error('Error updating destination:', error);
      toast.error('Failed to update destination');
    }
  };

  const handleDeleteDestination = async (id) => {
    try {
      await destinationsAPI.delete(id);
      setDestinations(destinations.filter(dest => dest.id !== id));
      setSpecials(specials.filter(special => special.destination_id !== id));
      toast.success('Destination deleted successfully!');
    } catch (error) {
      console.error('Error deleting destination:', error);
      toast.error('Failed to delete destination');
    }
  };

  const handleToggleSpecial = async (destinationId) => {
    const existingSpecial = specials.find(s => s.destination_id === destinationId);
    try {
      if (existingSpecial) {
        await specialsAPI.deleteByDestination(destinationId);
        setSpecials(specials.filter(s => s.destination_id !== destinationId));
        toast.success('Removed from specials');
      } else {
        const newSpecial = await specialsAPI.create({
          destination_id: destinationId,
          discount: 20,
          end_date: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
          highlights: ['Special offer', 'Limited time', 'Book now']
        });
        setSpecials([...specials, newSpecial]);
        toast.success('Added to specials!');
      }
    } catch (error) {
      console.error('Error toggling special:', error);
      toast.error('Failed to update special');
    }
  };

  const handleUpdateSpecial = async (specialId, field, value) => {
    try {
      const updatedSpecial = specials.find(s => s.id === specialId);
      if (!updatedSpecial) return;

      const updateData = { [field]: field === 'discount' ? parseFloat(value) : value };
      const updated = await specialsAPI.update(specialId, updateData);
      
      setSpecials(specials.map(special =>
        special.id === specialId ? updated : special
      ));
    } catch (error) {
      console.error('Error updating special:', error);
      toast.error('Failed to update special');
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Admin Header */}
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex justify-between items-center">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">Admin Dashboard</h1>
              <p className="text-sm text-gray-600">Manage destinations and special offers</p>
            </div>
            <div className="flex items-center space-x-4">
              <Button variant="outline" onClick={() => navigate('/')}>
                <Home className="w-4 h-4 mr-2" />
                View Site
              </Button>
              <Button variant="outline" onClick={handleLogout}>
                <LogOut className="w-4 h-4 mr-2" />
                Logout
              </Button>
            </div>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Tabs defaultValue="destinations" className="space-y-6">
          <TabsList className="grid w-full max-w-md grid-cols-2">
            <TabsTrigger value="destinations">Destinations Gallery</TabsTrigger>
            <TabsTrigger value="specials">Weekly Specials</TabsTrigger>
          </TabsList>

          {/* Destinations Management */}
          <TabsContent value="destinations" className="space-y-6">
            <div className="flex justify-between items-center">
              <div>
                <h2 className="text-xl font-semibold">Manage Destinations</h2>
                <p className="text-sm text-gray-600">Add, edit, or remove destinations from your gallery</p>
              </div>
              <Dialog open={isAddDialogOpen} onOpenChange={setIsAddDialogOpen}>
                <DialogTrigger asChild>
                  <Button className="bg-cyan-600 hover:bg-cyan-700">
                    <Plus className="w-4 h-4 mr-2" />
                    Add Destination
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
                  <DialogHeader>
                    <DialogTitle>Add New Destination</DialogTitle>
                    <DialogDescription>
                      Fill in the details to add a new destination to your gallery
                    </DialogDescription>
                  </DialogHeader>
                  <div className="space-y-4 py-4">
                    <div className="grid grid-cols-2 gap-4">
                      <div className="space-y-2">
                        <label className="text-sm font-medium">Destination Name</label>
                        <Input
                          placeholder="e.g., Paris"
                          value={newDestination.name}
                          onChange={(e) => setNewDestination({ ...newDestination, name: e.target.value })}
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium">Location</label>
                        <Input
                          placeholder="e.g., France"
                          value={newDestination.location}
                          onChange={(e) => setNewDestination({ ...newDestination, location: e.target.value })}
                        />
                      </div>
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium">Description</label>
                      <Textarea
                        placeholder="Describe the destination..."
                        value={newDestination.description}
                        onChange={(e) => setNewDestination({ ...newDestination, description: e.target.value })}
                        rows={3}
                      />
                    </div>
                    <div className="space-y-2">
                      <label className="text-sm font-medium">Image URL</label>
                      <Input
                        placeholder="https://example.com/image.jpg"
                        value={newDestination.image}
                        onChange={(e) => setNewDestination({ ...newDestination, image: e.target.value })}
                      />
                    </div>
                    <div className="grid grid-cols-3 gap-4">
                      <div className="space-y-2">
                        <label className="text-sm font-medium">Category</label>
                        <Select
                          value={newDestination.category}
                          onValueChange={(value) => setNewDestination({ ...newDestination, category: value })}
                        >
                          <SelectTrigger>
                            <SelectValue />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="City">City</SelectItem>
                            <SelectItem value="Beach">Beach</SelectItem>
                            <SelectItem value="Adventure">Adventure</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium">Rating</label>
                        <Input
                          type="number"
                          step="0.1"
                          min="0"
                          max="5"
                          value={newDestination.rating}
                          onChange={(e) => setNewDestination({ ...newDestination, rating: e.target.value })}
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="text-sm font-medium">Price (USD)</label>
                        <Input
                          type="number"
                          value={newDestination.price}
                          onChange={(e) => setNewDestination({ ...newDestination, price: e.target.value })}
                        />
                      </div>
                    </div>
                    <Button onClick={handleAddDestination} className="w-full bg-cyan-600 hover:bg-cyan-700">
                      Add Destination
                    </Button>
                  </div>
                </DialogContent>
              </Dialog>
            </div>

            {loading ? (
              <div className="text-center py-12">
                <p className="text-gray-600">Loading destinations...</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {destinations.map((destination) => (
                <Card key={destination.id} className="overflow-hidden">
                  <div className="relative">
                    <img
                      src={destination.image}
                      alt={destination.name}
                      className="w-full h-48 object-cover"
                    />
                    <Badge className="absolute top-2 right-2 bg-cyan-600">
                      {destination.category}
                    </Badge>
                  </div>
                  <CardHeader>
                    <CardTitle className="flex items-start justify-between">
                      <div>
                        <div className="text-lg">{destination.name}</div>
                        <div className="text-sm font-normal text-gray-600 flex items-center mt-1">
                          <MapPin className="w-3 h-3 mr-1" />
                          {destination.location}
                        </div>
                      </div>
                      <div className="flex items-center space-x-1">
                        <Star className="w-4 h-4 fill-yellow-400 text-yellow-400" />
                        <span className="text-sm font-semibold">{destination.rating}</span>
                      </div>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <p className="text-sm text-gray-600 mb-4 line-clamp-2">{destination.description}</p>
                    <div className="flex items-center justify-between mb-4">
                      <span className="text-xl font-bold text-cyan-600">${destination.price}</span>
                      {specials.some(s => s.destination_id === destination.id) && (
                        <Badge variant="outline" className="border-red-500 text-red-500">Special</Badge>
                      )}
                    </div>
                    <div className="flex space-x-2">
                      <Button
                        size="sm"
                        variant="outline"
                        className="flex-1"
                        onClick={() => handleEditDestination(destination)}
                      >
                        <Edit className="w-3 h-3 mr-1" />
                        Edit
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        className="flex-1 border-red-200 text-red-600 hover:bg-red-50"
                        onClick={() => handleDeleteDestination(destination.id)}
                      >
                        <Trash2 className="w-3 h-3 mr-1" />
                        Delete
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
          </TabsContent>

          {/* Specials Management */}
          <TabsContent value="specials" className="space-y-6">
            <div>
              <h2 className="text-xl font-semibold mb-2">Weekly Specials</h2>
              <p className="text-sm text-gray-600">Select destinations to feature as special offers</p>
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {destinations.map((destination) => {
                const special = specials.find(s => s.destination_id === destination.id);
                return (
                  <Card key={destination.id}>
                    <CardContent className="pt-6">
                      <div className="flex space-x-4">
                        <img
                          src={destination.image}
                          alt={destination.name}
                          className="w-32 h-32 object-cover rounded-lg"
                        />
                        <div className="flex-1 space-y-3">
                          <div>
                            <h3 className="font-semibold text-lg">{destination.name}</h3>
                            <p className="text-sm text-gray-600">{destination.location}</p>
                          </div>
                          
                          {special ? (
                            <div className="space-y-3">
                              <div className="grid grid-cols-2 gap-2">
                                <div>
                                  <label className="text-xs text-gray-600">Discount %</label>
                                  <Input
                                    type="number"
                                    value={special.discount}
                                    onChange={(e) => handleUpdateSpecial(special.id, 'discount', e.target.value)}
                                    className="h-8"
                                  />
                                </div>
                                <div>
                                  <label className="text-xs text-gray-600">End Date</label>
                                  <Input
                                    type="date"
                                    value={special.end_date}
                                    onChange={(e) => handleUpdateSpecial(special.id, 'end_date', e.target.value)}
                                    className="h-8"
                                  />
                                </div>
                              </div>
                              <Button
                                size="sm"
                                variant="outline"
                                className="w-full border-red-200 text-red-600 hover:bg-red-50"
                                onClick={() => handleToggleSpecial(destination.id)}
                              >
                                Remove from Specials
                              </Button>
                            </div>
                          ) : (
                            <Button
                              size="sm"
                              className="w-full bg-cyan-600 hover:bg-cyan-700"
                              onClick={() => handleToggleSpecial(destination.id)}
                            >
                              <Tag className="w-3 h-3 mr-1" />
                              Add to Specials
                            </Button>
                          )}
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </TabsContent>
        </Tabs>
      </div>

      {/* Edit Dialog */}
      {isEditMode && editingDestination && (
        <Dialog open={isEditMode} onOpenChange={setIsEditMode}>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Edit Destination</DialogTitle>
              <DialogDescription>
                Update the destination details
              </DialogDescription>
            </DialogHeader>
            <div className="space-y-4 py-4">
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Destination Name</label>
                  <Input
                    value={editingDestination.name}
                    onChange={(e) => setEditingDestination({ ...editingDestination, name: e.target.value })}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Location</label>
                  <Input
                    value={editingDestination.location}
                    onChange={(e) => setEditingDestination({ ...editingDestination, location: e.target.value })}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Description</label>
                <Textarea
                  value={editingDestination.description}
                  onChange={(e) => setEditingDestination({ ...editingDestination, description: e.target.value })}
                  rows={3}
                />
              </div>
              <div className="space-y-2">
                <label className="text-sm font-medium">Image URL</label>
                <Input
                  value={editingDestination.image}
                  onChange={(e) => setEditingDestination({ ...editingDestination, image: e.target.value })}
                />
              </div>
              <div className="grid grid-cols-3 gap-4">
                <div className="space-y-2">
                  <label className="text-sm font-medium">Category</label>
                  <Select
                    value={editingDestination.category}
                    onValueChange={(value) => setEditingDestination({ ...editingDestination, category: value })}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="City">City</SelectItem>
                      <SelectItem value="Beach">Beach</SelectItem>
                      <SelectItem value="Adventure">Adventure</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Rating</label>
                  <Input
                    type="number"
                    step="0.1"
                    min="0"
                    max="5"
                    value={editingDestination.rating}
                    onChange={(e) => setEditingDestination({ ...editingDestination, rating: parseFloat(e.target.value) })}
                  />
                </div>
                <div className="space-y-2">
                  <label className="text-sm font-medium">Price (USD)</label>
                  <Input
                    type="number"
                    value={editingDestination.price}
                    onChange={(e) => setEditingDestination({ ...editingDestination, price: parseFloat(e.target.value) })}
                  />
                </div>
              </div>
              <div className="flex space-x-2">
                <Button onClick={handleSaveEdit} className="flex-1 bg-cyan-600 hover:bg-cyan-700">
                  <Save className="w-4 h-4 mr-2" />
                  Save Changes
                </Button>
                <Button onClick={() => setIsEditMode(false)} variant="outline" className="flex-1">
                  <X className="w-4 h-4 mr-2" />
                  Cancel
                </Button>
              </div>
            </div>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
};

export default AdminDashboard;
