import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } 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, Users, Clock, Calendar, Phone, Mail } from 'lucide-react';
import { toast } from 'sonner';

interface Staff {
  id: string;
  name: string;
  role: string;
  email: string;
  phone: string;
  status: 'active' | 'inactive' | 'on_leave';
  shift: string;
  hiredDate: Date;
  hourlyRate: number;
}

const StaffManagement = () => {
  const [staff, setStaff] = useState<Staff[]>([
    {
      id: '1',
      name: 'Carlos Martínez',
      role: 'Mesero',
      email: 'carlos@restaurant.com',
      phone: '+34 600 123 456',
      status: 'active',
      shift: 'Mañana',
      hiredDate: new Date('2023-01-15'),
      hourlyRate: 12.50
    },
    {
      id: '2',
      name: 'Ana López',
      role: 'Mesera',
      email: 'ana@restaurant.com',
      phone: '+34 600 234 567',
      status: 'active',
      shift: 'Tarde',
      hiredDate: new Date('2023-03-20'),
      hourlyRate: 12.50
    },
    {
      id: '3',
      name: 'Miguel Rodríguez',
      role: 'Chef',
      email: 'miguel@restaurant.com',
      phone: '+34 600 345 678',
      status: 'active',
      shift: 'Completo',
      hiredDate: new Date('2022-06-10'),
      hourlyRate: 18.00
    },
    {
      id: '4',
      name: 'Laura García',
      role: 'Ayudante de Cocina',
      email: 'laura@restaurant.com',
      phone: '+34 600 456 789',
      status: 'on_leave',
      shift: 'Mañana',
      hiredDate: new Date('2023-09-05'),
      hourlyRate: 10.50
    }
  ]);

  const roles = ['Mesero', 'Chef', 'Ayudante de Cocina', 'Bartender', 'Host', 'Gerente'];
  const shifts = ['Mañana', 'Tarde', 'Noche', 'Completo'];

  const activeStaff = staff.filter(s => s.status === 'active').length;
  const onLeave = staff.filter(s => s.status === 'on_leave').length;

  const getStatusColor = (status: Staff['status']) => {
    switch (status) {
      case 'active': return 'default';
      case 'inactive': return 'secondary';
      case 'on_leave': return 'outline';
      default: return 'secondary';
    }
  };

  const getStatusLabel = (status: Staff['status']) => {
    switch (status) {
      case 'active': return 'Activo';
      case 'inactive': return 'Inactivo';
      case 'on_leave': return 'De Permiso';
      default: return status;
    }
  };

  const updateStatus = (staffId: string, newStatus: Staff['status']) => {
    setStaff(staff.map(s =>
      s.id === staffId ? { ...s, status: newStatus } : s
    ));
    toast.success('Estado actualizado');
  };

  const getMonthsEmployed = (hiredDate: Date) => {
    const months = Math.floor((Date.now() - hiredDate.getTime()) / (1000 * 60 * 60 * 24 * 30));
    return months;
  };

  return (
    <div className="space-y-6">
      {/* Stats */}
      <div className="grid gap-4 md:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Personal</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{staff.length}</div>
            <p className="text-xs text-muted-foreground">empleados totales</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Activos</CardTitle>
            <Users className="h-4 w-4 text-green-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-500">{activeStaff}</div>
            <p className="text-xs text-muted-foreground">trabajando hoy</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">De Permiso</CardTitle>
            <Clock className="h-4 w-4 text-orange-500" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-500">{onLeave}</div>
            <p className="text-xs text-muted-foreground">ausentes hoy</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Costo Hora</CardTitle>
            <Calendar className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              €{staff.reduce((sum, s) => sum + s.hourlyRate, 0).toFixed(2)}
            </div>
            <p className="text-xs text-muted-foreground">por hora total</p>
          </CardContent>
        </Card>
      </div>

      {/* Actions */}
      <div className="flex justify-between items-center">
        <div>
          <h3 className="text-lg font-semibold">Equipo de Trabajo</h3>
          <p className="text-sm text-muted-foreground">Gestiona tu personal del restaurante</p>
        </div>
        <Dialog>
          <DialogTrigger asChild>
            <Button className="gap-2">
              <Plus className="h-4 w-4" />
              Nuevo Empleado
            </Button>
          </DialogTrigger>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>Agregar Nuevo Empleado</DialogTitle>
            </DialogHeader>
            <div className="space-y-4">
              <div>
                <Label htmlFor="staff-name">Nombre Completo</Label>
                <Input id="staff-name" placeholder="Ej: Carlos Martínez" />
              </div>
              <div>
                <Label htmlFor="staff-role">Puesto</Label>
                <Select>
                  <SelectTrigger id="staff-role">
                    <SelectValue placeholder="Seleccionar puesto" />
                  </SelectTrigger>
                  <SelectContent>
                    {roles.map(role => (
                      <SelectItem key={role} value={role}>{role}</SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="staff-email">Email</Label>
                  <Input id="staff-email" type="email" placeholder="email@ejemplo.com" />
                </div>
                <div>
                  <Label htmlFor="staff-phone">Teléfono</Label>
                  <Input id="staff-phone" placeholder="+34 600 123 456" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="staff-shift">Turno</Label>
                  <Select>
                    <SelectTrigger id="staff-shift">
                      <SelectValue placeholder="Turno" />
                    </SelectTrigger>
                    <SelectContent>
                      {shifts.map(shift => (
                        <SelectItem key={shift} value={shift}>{shift}</SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="staff-rate">Tarifa por Hora (€)</Label>
                  <Input id="staff-rate" type="number" step="0.50" placeholder="12.50" />
                </div>
              </div>
              <Button className="w-full">Agregar Empleado</Button>
            </div>
          </DialogContent>
        </Dialog>
      </div>

      {/* Staff List */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {staff.map((member) => (
          <Card key={member.id}>
            <CardHeader>
              <div className="flex justify-between items-start">
                <div>
                  <CardTitle className="text-lg">{member.name}</CardTitle>
                  <p className="text-sm text-muted-foreground">{member.role}</p>
                </div>
                <Badge variant={getStatusColor(member.status)}>
                  {getStatusLabel(member.status)}
                </Badge>
              </div>
            </CardHeader>
            <CardContent className="space-y-3">
              <div className="space-y-2 text-sm">
                <div className="flex items-center gap-2">
                  <Mail className="h-3 w-3 text-muted-foreground" />
                  <span className="text-xs">{member.email}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Phone className="h-3 w-3 text-muted-foreground" />
                  <span className="text-xs">{member.phone}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Clock className="h-3 w-3 text-muted-foreground" />
                  <span>Turno: {member.shift}</span>
                </div>
                <div className="flex items-center gap-2">
                  <Calendar className="h-3 w-3 text-muted-foreground" />
                  <span>{getMonthsEmployed(member.hiredDate)} meses en la empresa</span>
                </div>
              </div>

              <div className="p-3 bg-muted rounded-lg">
                <div className="text-xs text-muted-foreground">Tarifa por Hora</div>
                <div className="text-xl font-bold text-primary">€{member.hourlyRate.toFixed(2)}</div>
              </div>

              <div className="flex gap-2">
                <Select
                  value={member.status}
                  onValueChange={(value) => updateStatus(member.id, value as Staff['status'])}
                >
                  <SelectTrigger className="flex-1">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="active">Activo</SelectItem>
                    <SelectItem value="on_leave">De Permiso</SelectItem>
                    <SelectItem value="inactive">Inactivo</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  );
};

export default StaffManagement;
