'use client';

import { useState, useEffect, useCallback } from 'react';
import {
  Printer, Monitor, Plus, Edit2, Save, X,
  Ban, RotateCcw, MapPin, Wifi
} from 'lucide-react';

interface Station {
  id: string;
  name: string;
  stationType: string;
  location: string | null;
  layoutConfig: any;
  printerConfig: any;
  isActive: boolean;
  _count?: { orders: number };
}

export default function POSStationsPage() {
  const [stations, setStations] = useState<Station[]>([]);
  const [loading, setLoading] = useState(true);
  const [editing, setEditing] = useState<Partial<Station> | null>(null);
  const [notification, setNotification] = useState<{ message: string; type: 'success' | 'error' } | null>(null);

  const showNotification = (message: string, type: 'success' | 'error' = 'success') => {
    setNotification({ message, type });
    setTimeout(() => setNotification(null), 3000);
  };

  const fetchStations = useCallback(async () => {
    try {
      const res = await fetch('/api/pos/stations');
      const data = await res.json();
      if (data.stations) setStations(data.stations);
    } catch {
      showNotification('Failed to load stations', 'error');
    } finally {
      setLoading(false);
    }
  }, []);

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

  const saveStation = async () => {
    if (!editing?.name) return;
    try {
      const method = editing.id ? 'PUT' : 'POST';
      const res = await fetch('/api/pos/stations', {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(editing),
      });
      if (res.ok) {
        showNotification(editing.id ? 'Station updated' : 'Station created');
        setEditing(null);
        fetchStations();
      } else {
        const err = await res.json();
        showNotification(err.error || 'Failed to save', 'error');
      }
    } catch {
      showNotification('Failed to save station', 'error');
    }
  };

  const toggleActive = async (station: Station) => {
    try {
      await fetch('/api/pos/stations', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ id: station.id, isActive: !station.isActive }),
      });
      showNotification(station.isActive ? 'Station deactivated' : 'Station reactivated');
      fetchStations();
    } catch {
      showNotification('Failed to update station', 'error');
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" />
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {notification && (
        <div className={`fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg text-white text-sm font-medium ${
          notification.type === 'success' ? 'bg-green-600' : 'bg-red-600'
        }`}>
          {notification.message}
        </div>
      )}

      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white flex items-center gap-3">
            <Printer className="w-7 h-7 text-blue-400" />
            POS Stations
          </h1>
          <p className="text-gray-400 mt-1">Manage registers, kitchen displays, and printer configurations</p>
        </div>
        <button
          onClick={() => setEditing({ name: '', stationType: 'register', location: '', layoutConfig: {}, printerConfig: {} })}
          className="flex items-center gap-2 px-4 py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors"
        >
          <Plus className="w-4 h-4" /> Add Station
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {stations.map(station => (
          <div
            key={station.id}
            className={`bg-black/40 border rounded-xl p-5 transition-all ${
              station.isActive ? 'border-white/10' : 'border-red-500/30 opacity-60'
            }`}
          >
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-3">
                <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
                  station.stationType === 'register' ? 'bg-blue-500/20 text-blue-400' :
                  station.stationType === 'kitchen_display' ? 'bg-orange-500/20 text-orange-400' :
                  'bg-orange-500/20 text-orange-400'
                }`}>
                  {station.stationType === 'register' ? <Monitor className="w-5 h-5" /> : <Printer className="w-5 h-5" />}
                </div>
                <div>
                  <h3 className="font-semibold text-white">{station.name}</h3>
                  <p className="text-xs text-gray-500 capitalize">{station.stationType.replace('_', ' ')}</p>
                </div>
              </div>
              <div className="flex items-center gap-1">
                <button
                  onClick={() => setEditing(station)}
                  className="p-1.5 hover:bg-white/10 rounded-lg transition-colors text-gray-400 hover:text-white"
                >
                  <Edit2 className="w-4 h-4" />
                </button>
                <button
                  onClick={() => toggleActive(station)}
                  className={`p-1.5 hover:bg-white/10 rounded-lg transition-colors ${
                    station.isActive ? 'text-gray-400 hover:text-red-400' : 'text-red-400 hover:text-green-400'
                  }`}
                >
                  {station.isActive ? <Ban className="w-4 h-4" /> : <RotateCcw className="w-4 h-4" />}
                </button>
              </div>
            </div>
            {station.location && (
              <div className="flex items-center gap-2 text-xs text-gray-400 mb-2">
                <MapPin className="w-3 h-3" /> {station.location}
              </div>
            )}
            <div className="flex items-center gap-2 text-xs text-gray-500">
              <Wifi className="w-3 h-3" />
              {station._count?.orders || 0} orders processed
            </div>
            {!station.isActive && (
              <div className="mt-2 text-xs text-red-400 flex items-center gap-1">
                <Ban className="w-3 h-3" /> Inactive
              </div>
            )}
          </div>
        ))}
      </div>

      {stations.length === 0 && (
        <div className="text-center py-12 text-gray-500">
          <Printer className="w-8 h-8 mx-auto mb-2 opacity-50" />
          <p>No stations configured. Add your first register or kitchen display.</p>
        </div>
      )}

      {/* Edit Modal */}
      {editing && (
        <div className="fixed inset-0 bg-black/70 flex items-center justify-center z-50" onClick={() => setEditing(null)}>
          <div className="bg-gray-900 border border-white/10 rounded-2xl p-6 w-full max-w-md" onClick={e => e.stopPropagation()}>
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-white">{editing.id ? 'Edit Station' : 'New Station'}</h2>
              <button onClick={() => setEditing(null)} className="text-gray-400 hover:text-white"><X className="w-5 h-5" /></button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm text-gray-400 mb-1">Station Name</label>
                <input
                  type="text"
                  value={editing.name || ''}
                  onChange={e => setEditing({ ...editing, name: e.target.value })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                  placeholder="Register 1"
                />
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Type</label>
                <select
                  value={editing.stationType || 'register'}
                  onChange={e => setEditing({ ...editing, stationType: e.target.value })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                >
                  <option value="register" className="bg-gray-900">Register</option>
                  <option value="kitchen_display" className="bg-gray-900">Kitchen Display</option>
                  <option value="bar_display" className="bg-gray-900">Bar Display</option>
                </select>
              </div>
              <div>
                <label className="block text-sm text-gray-400 mb-1">Location</label>
                <input
                  type="text"
                  value={editing.location || ''}
                  onChange={e => setEditing({ ...editing, location: e.target.value })}
                  className="w-full px-3 py-2.5 bg-black/40 border border-white/10 rounded-lg text-white text-sm focus:outline-none focus:border-blue-500"
                  placeholder="Front Counter"
                />
              </div>
              <button
                onClick={saveStation}
                className="w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors flex items-center justify-center gap-2"
              >
                <Save className="w-4 h-4" /> {editing.id ? 'Update Station' : 'Create Station'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
