import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { DndContext, DragOverlay, type DragEndEvent, type DragStartEvent } from '@dnd-kit/core';
import { useDesignStore } from '../store/designStore';
import StonePanel from './StonePanel';
import ModelView from './ModelView';
import SettingsPanel from './SettingsPanel';
import Cart from './Cart';
import OrderButton from './OrderButton';
import OrderModal from './OrderModal';
import type { JewelryType, Stone } from '../types';

const VALID_TYPES: JewelryType[] = ['bileklik', 'kolye', 'tesbih'];

function DesignEditor() {
  const { type } = useParams<{ type: string }>();
  const setJewelryType = useDesignStore((s) => s.setJewelryType);
  const slots = useDesignStore((s) => s.slots);
  const placeStone = useDesignStore((s) => s.placeStone);

  const [activeStone, setActiveStone] = useState<Stone | null>(null);
  const [showOrderModal, setShowOrderModal] = useState(false);

  useEffect(() => {
    if (type && VALID_TYPES.includes(type as JewelryType)) {
      setJewelryType(type as JewelryType);
    }
  }, [type, setJewelryType]);

  const isFull = slots.length > 0 && slots.every((s) => s.stone !== null);

  const handleDragStart = useCallback((event: DragStartEvent) => {
    const stone = event.active.data.current?.stone as Stone | undefined;
    setActiveStone(stone ?? null);
  }, []);

  const handleDragEnd = useCallback(
    (event: DragEndEvent) => {
      setActiveStone(null);

      const { over, active } = event;
      if (!over) return;

      const droppableId = String(over.id);
      if (!droppableId.startsWith('slot-')) return;

      const slotIndex = over.data.current?.slotIndex as number | undefined;
      if (slotIndex === undefined) return;

      const stone = active.data.current?.stone as Stone | undefined;
      if (!stone) return;

      const slot = slots[slotIndex];
      if (!slot || slot.stone !== null) return;

      if (isFull) return;

      placeStone(slotIndex, stone);
    },
    [slots, isFull, placeStone],
  );

  return (
    <DndContext onDragStart={handleDragStart} onDragEnd={handleDragEnd}>
      <div className="flex flex-col md:flex-row min-h-screen gap-2 p-2">
        {/* Sol Panel — Taş Kataloğu */}
        <aside className="w-full md:w-64 shrink-0 rounded-xl bg-white/10 backdrop-blur-sm p-4">
          <StonePanel />
        </aside>

        {/* Orta Panel — Takı Modeli */}
        <main className="flex-1 rounded-xl bg-white/10 backdrop-blur-sm p-4 text-white flex items-center justify-center overflow-hidden">
          <ModelView />
          {isFull && (
            <div className="absolute top-4 left-1/2 -translate-x-1/2 bg-red-500/90 text-white text-sm px-4 py-2 rounded-lg">
              Kapasite doldu — yeni taş eklenemez
            </div>
          )}
        </main>

        {/* Sağ Panel — Ayarlar & Sepet */}
        <aside className="w-full md:w-72 shrink-0 rounded-xl bg-white/10 backdrop-blur-sm p-4 text-white">
          <h2 className="text-lg font-semibold mb-4">Ayarlar & Sepet</h2>
          <SettingsPanel />
          <hr className="border-white/10 my-4" />
          <Cart />
          <div className="mt-4">
            <OrderButton onClick={() => setShowOrderModal(true)} />
          </div>
        </aside>
      </div>

      <DragOverlay>
        {activeStone ? (
          activeStone.image.startsWith('#') ? (
            <div
              className="w-12 h-12 rounded-full ring-2 ring-purple-400 opacity-80 shadow-lg"
              style={{ backgroundColor: activeStone.image }}
            />
          ) : (
            <img
              src={activeStone.image}
              alt={activeStone.name}
              className="w-12 h-12 rounded-full object-cover ring-2 ring-purple-400 opacity-80"
            />
          )
        ) : null}
      </DragOverlay>

      {showOrderModal && (
        <OrderModal onClose={() => setShowOrderModal(false)} />
      )}
    </DndContext>
  );
}

export default DesignEditor;
