'use client';

import { useCallback, useEffect, useState } from 'react';
import { Plus, Edit, Trash2, MapPin, Users, Clock } from 'lucide-react';
import { api } from '@/lib/api';
import { RoomDialog } from '@/components/rooms/room-dialog';
import { DeleteRoomDialog } from '@/components/rooms/delete-room-dialog';

type Room = {
  id: string;
  name: string;
  location: string;
  capacity: number;
  type: string;
  equipment: string[];
  status: 'available' | 'occupied' | 'maintenance';
  workingHours: string;
};

type RoomsResponse = {
  data: Room[];
  hasMore: boolean;
  nextCursor: string | null;
};

const statusMap: Record<string, { label: string; className: string }> = {
  available: { label: 'Свободен', className: 'bg-green-100 text-green-800' },
  occupied: { label: 'Занят', className: 'bg-orange-100 text-orange-800' },
  maintenance: { label: 'Обслуживание', className: 'bg-red-100 text-red-800' },
};

export default function RoomsPage(): React.JSX.Element {
  const [rooms, setRooms] = useState<Room[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [showAddDialog, setShowAddDialog] = useState(false);
  const [editRoom, setEditRoom] = useState<Room | null>(null);
  const [deleteRoom, setDeleteRoom] = useState<Room | null>(null);

  const loadRooms = useCallback(() => {
    setLoading(true);
    api.get<RoomsResponse>('/rooms')
      .then((res) => {
        setRooms(res.data ?? []);
        setError(null);
      })
      .catch((err) => {
        setRooms([]);
        setError(err instanceof Error ? err.message : 'Не удалось загрузить залы');
      })
      .finally(() => setLoading(false));
  }, []);

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

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <p className="text-error text-sm mb-2">{error}</p>
          <button
            onClick={loadRooms}
            className="text-sm text-primary hover:underline"
          >
            Попробовать снова
          </button>
        </div>
      </div>
    );
  }

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">Залы и локации</h1>
        <button
          onClick={() => setShowAddDialog(true)}
          className="flex items-center gap-2 bg-primary text-white px-4 py-2.5 rounded-xl text-sm font-medium hover:bg-primary/90 transition-colors"
        >
          <Plus className="h-4 w-4" />
          Добавить зал
        </button>
      </div>

      {rooms.length === 0 && (
        <div className="text-center py-12 text-muted text-sm">
          Нет залов
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {rooms.map((room) => {
          const status = statusMap[room.status] ?? { label: 'Неизвестно', className: 'bg-gray-100 text-gray-800' };
          return (
            <div
              key={room.id}
              className="bg-card rounded-xl p-6 shadow-sm border border-border flex flex-col"
            >
              <div className="flex items-start justify-between mb-3">
                <h2 className="text-base font-semibold text-gray-900 leading-tight">
                  {room.name}
                </h2>
                <span className={`shrink-0 ml-2 inline-flex px-2 py-0.5 rounded-full text-xs font-medium ${status.className}`}>
                  {status.label}
                </span>
              </div>

              <div className="space-y-2 mb-4 flex-1">
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <MapPin className="h-4 w-4 text-muted shrink-0" />
                  {room.location}
                </div>
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <Users className="h-4 w-4 text-muted shrink-0" />
                  Вместимость: {room.capacity} чел.
                </div>
                <div className="flex items-center gap-2 text-sm text-gray-600">
                  <Clock className="h-4 w-4 text-muted shrink-0" />
                  {room.workingHours}
                </div>
              </div>

              <div className="flex flex-wrap gap-1.5 mb-4">
                {(room.equipment ?? []).map((eq) => (
                  <span
                    key={eq}
                    className="bg-gray-100 text-gray-700 px-2 py-0.5 rounded text-xs"
                  >
                    {eq}
                  </span>
                ))}
              </div>

              <div className="flex gap-2 pt-4 border-t border-border">
                <button
                  onClick={() => setEditRoom(room)}
                  className="flex-1 flex items-center justify-center gap-1.5 px-3 py-2 rounded-lg border border-border text-sm text-gray-700 hover:bg-gray-50 transition-colors"
                >
                  <Edit className="h-3.5 w-3.5" />
                  Изменить
                </button>
                <button
                  onClick={() => setDeleteRoom(room)}
                  className="flex items-center justify-center p-2 rounded-lg border border-border text-error hover:bg-red-50 transition-colors"
                >
                  <Trash2 className="h-3.5 w-3.5" />
                </button>
              </div>
            </div>
          );
        })}
      </div>

      <RoomDialog
        open={showAddDialog}
        onClose={() => setShowAddDialog(false)}
        onSaved={loadRooms}
      />

      <RoomDialog
        open={!!editRoom}
        onClose={() => setEditRoom(null)}
        onSaved={loadRooms}
        room={editRoom}
      />

      <DeleteRoomDialog
        open={!!deleteRoom}
        onClose={() => setDeleteRoom(null)}
        onDeleted={loadRooms}
        room={deleteRoom}
      />
    </div>
  );
}
