import { useEffect, useRef } from 'react';
import { toast } from 'sonner';
import { useRackStore } from '../../store/useRackStore';
import { RackToolbar } from './RackToolbar';
import { RackColumn } from './RackColumn';
import { RackSkeleton } from '../ui/Skeleton';

export function RackPlanner() {
  const { racks, loading, fetchRacks } = useRackStore();
  const canvasRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    fetchRacks().catch(() => toast.error('Failed to load racks'));
  }, [fetchRacks]);

  return (
    <div className="flex flex-col h-screen bg-[#0f1117]">
      <RackToolbar rackCanvasRef={canvasRef} />

      <div className="flex flex-1 overflow-hidden">
        {/* Main rack canvas */}
        <div className="flex-1 overflow-auto">
          {loading ? (
            <RackSkeleton />
          ) : racks.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full gap-3 text-center px-4">
              <div className="w-16 h-16 bg-slate-800 rounded-xl border border-slate-700 flex items-center justify-center">
                <svg width="32" height="32" viewBox="0 0 18 18" fill="none">
                  <rect x="1" y="2" width="16" height="3" rx="1" fill="#475569" />
                  <rect x="1" y="7" width="16" height="3" rx="1" fill="#475569" opacity="0.7" />
                  <rect x="1" y="12" width="16" height="3" rx="1" fill="#475569" opacity="0.4" />
                </svg>
              </div>
              <div>
                <p className="text-slate-300 font-medium">No racks yet</p>
                <p className="text-slate-500 text-sm mt-1">
                  Click <strong className="text-slate-300">Add Rack</strong> in the toolbar to create your first rack.
                </p>
              </div>
            </div>
          ) : (
            <div
              ref={canvasRef}
              className="flex gap-4 p-4 min-h-full items-start"
              style={{ background: '#0f1117' }}
            >
              {racks.map((rack) => (
                <RackColumn key={rack.id} rack={rack} />
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
