import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Plus, Edit, Trash2, Grid3x3 } from 'lucide-react';
import { toast } from 'sonner';

interface Table {
  id: string;
  number: number;
  seats: number;
  section: string;
  status: 'available' | 'occupied' | 'reserved' | 'maintenance';
  position: { x: number; y: number };
}

const TableConfiguration = () => {
  const [tables, setTables] = useState<Table[]>([
    { id: '1', number: 1, seats: 4, section: 'Interior', status: 'available', position: { x: 50, y: 50 } },
    { id: '2', number: 2, seats: 2, section: 'Interior', status: 'occupied', position: { x: 200, y: 50 } },
    { id: '3', number: 3, seats: 6, section: 'Terraza', status: 'available', position: { x: 50, y: 200 } },
    { id: '4', number: 4, seats: 4, section: 'Terraza', status: 'reserved', position: { x: 200, y: 200 } },
    { id: '5', number: 5, seats: 8, section: 'VIP', status: 'available', position: { x: 350, y: 125 } }
  ]);

  const [editingTable, setEditingTable] = useState<Table | null>(null);

  const getStatusColor = (status: Table['status']) => {
    switch (status) {
      case 'available': return 'bg-green-500';
      case 'occupied': return 'bg-red-500';
      case 'reserved': return 'bg-yellow-500';
      case 'maintenance': return 'bg-gray-500';
      default: return 'bg-gray-500';
    }
  };

  const getStatusLabel = (status: Table['status']) => {
    switch (status) {
      case 'available': return 'Disponible';
      case 'occupied': return 'Ocupada';
      case 'reserved': return 'Reservada';
      case 'maintenance': return 'Mantenimiento';
      default: return status;
    }
  };

  const addTable = () => {
    const newTable: Table = {
      id: String(tables.length + 1),
      number: tables.length + 1,
      seats: 4,
      section: 'Interior',
      status: 'available',
      position: { x: 100, y: 100 }
    };
    setTables([...tables, newTable]);
    toast.success('Mesa agregada correctamente');
  };

  const updateTable = (updatedTable: Table) => {
    setTables(tables.map(t => t.id === updatedTable.id ? updatedTable : t));
    setEditingTable(null);
    toast.success('Mesa actualizada correctamente');
  };

  const deleteTable = (tableId: string) => {
    setTables(tables.filter(t => t.id !== tableId));
    toast.success('Mesa eliminada correctamente');
  };

  const changeStatus = (tableId: string, newStatus: Table['status']) => {
    setTables(tables.map(t => 
      t.id === tableId ? { ...t, status: newStatus } : t
    ));
    toast.success('Estado actualizado');
  };

  const sections = ['Interior', 'Terraza', 'VIP', 'Bar'];

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-lg font-semibold">Layout del Restaurante</h3>
          <p className="text-sm text-muted-foreground">
            {tables.length} mesas configuradas
          </p>
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              Nueva Mesa
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Agregar Nueva Mesa</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="table-number">Número de Mesa</Label>
                <Input id="table-number" type="number" defaultValue={tables.length + 1} />
              </div>
              <div>
                <Label htmlFor="table-seats">Capacidad (personas)</Label>
                <Input id="table-seats" type="number" defaultValue={4} />
              </div>
              <div>
                <Label htmlFor="table-section">Sección</Label>
                <Select defaultValue="Interior">
                  <SelectTrigger id="table-section">
                    <SelectValue placeholder="Seleccionar sección" />
                  </SelectTrigger>
                  <SelectContent>
                    {sections.map(section => (
                      <SelectItem key={section} value={section}>{section}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <Button onClick={addTable} className="w-full">Agregar Mesa</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Visual Layout */}
      <Card>
        <CardContent className="p-6">
          <div className="relative bg-muted/30 rounded-lg" style={{ height: '400px' }}>
            <div className="absolute top-2 left-2 flex gap-2 text-xs">
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 rounded bg-green-500"></div>
                <span>Disponible</span>
              </div>
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 rounded bg-red-500"></div>
                <span>Ocupada</span>
              </div>
              <div className="flex items-center gap-1">
                <div className="w-3 h-3 rounded bg-yellow-500"></div>
                <span>Reservada</span>
              </div>
            </div>
            
            {tables.map((table) => (
              <div
                key={table.id}
                className="absolute cursor-move hover:scale-110 transition-transform"
                draggable
                onDragStart={(e) => {
                  e.dataTransfer.effectAllowed = 'move';
                  e.dataTransfer.setData('tableId', table.id);
                }}
                onDragEnd={(e) => {
                  const rect = e.currentTarget.parentElement?.getBoundingClientRect();
                  if (rect) {
                    const x = Math.max(0, Math.min(e.clientX - rect.left - 40, rect.width - 80));
                    const y = Math.max(0, Math.min(e.clientY - rect.top - 40, rect.height - 80));
                    setTables(tables.map(t => 
                      t.id === table.id ? { ...t, position: { x, y } } : t
                    ));
                  }
                }}
                style={{
                  left: `${table.position.x}px`,
                  top: `${table.position.y}px`
                }}
              >
                <div className={`${getStatusColor(table.status)} text-white rounded-lg p-3 shadow-lg`}>
                  <div className="text-center">
                    <div className="font-bold">#{table.number}</div>
                    <div className="text-xs">{table.seats} personas</div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Tables List */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {tables.map((table) => (
          <Card key={table.id}>
            <CardContent className="p-4">
              <div className="flex justify-between items-start mb-3">
                <div>
                  <h4 className="font-semibold text-lg">Mesa #{table.number}</h4>
                  <p className="text-sm text-muted-foreground">{table.section}</p>
                </div>
                <div className="flex gap-1">
                  <Dialog>
                    <DialogTrigger asChild>
                      <Button size="icon" variant="ghost" onClick={() => setEditingTable(table)}>
                        <Edit className="h-4 w-4" />
                      </Button>
                    </DialogTrigger>
                    <DialogContent>
                      <DialogHeader>
                        <DialogTitle>Editar Mesa #{table.number}</DialogTitle>
                      </DialogHeader>
                      <div className="space-y-4">
                        <div>
                          <Label>Capacidad</Label>
                          <Input type="number" defaultValue={table.seats} />
                        </div>
                        <div>
                          <Label>Sección</Label>
                          <Select defaultValue={table.section}>
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              {sections.map(section => (
                                <SelectItem key={section} value={section}>{section}</SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        </div>
                        <div>
                          <Label>Estado</Label>
                          <Select 
                            defaultValue={table.status}
                            onValueChange={(value) => changeStatus(table.id, value as Table['status'])}
                          >
                            <SelectTrigger>
                              <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                              <SelectItem value="available">Disponible</SelectItem>
                              <SelectItem value="occupied">Ocupada</SelectItem>
                              <SelectItem value="reserved">Reservada</SelectItem>
                              <SelectItem value="maintenance">Mantenimiento</SelectItem>
                            </SelectContent>
                          </Select>
                        </div>
                        <Button className="w-full">Guardar Cambios</Button>
                      </div>
                    </DialogContent>
                  </Dialog>
                  <Button 
                    size="icon" 
                    variant="ghost"
                    onClick={() => deleteTable(table.id)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              </div>

              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Capacidad:</span>
                  <span className="font-medium">{table.seats} personas</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Estado:</span>
                  <span className={`font-medium ${getStatusColor(table.status)} text-white px-2 py-0.5 rounded text-xs`}>
                    {getStatusLabel(table.status)}
                  </span>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default TableConfiguration;
