import { useState } from 'react';
import { useDesignStore } from '../store/designStore';
import { createOrder } from '../api/client';
import type { CreateOrderRequest } from '../types';

function isColor(str: string) {
  return str.startsWith('#') || str.startsWith('rgb');
}

interface OrderModalProps {
  onClose: () => void;
}

function OrderModal({ onClose }: OrderModalProps) {
  const jewelryType = useDesignStore((s) => s.jewelryType);
  const selectedTemplate = useDesignStore((s) => s.selectedTemplate);
  const size = useDesignStore((s) => s.size);
  const stoneSizeMm = useDesignStore((s) => s.stoneSizeMm);
  const slots = useDesignStore((s) => s.slots);

  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [customerNote, setCustomerNote] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const filledSlots = slots.filter((s) => s.stone !== null);

  const typeLabels: Record<string, string> = {
    bileklik: 'Bileklik',
    kolye: 'Kolye',
    tesbih: 'Tesbih',
  };

  async function handleConfirm() {
    if (!customerName.trim() || !customerPhone.trim()) {
      setError('Ad ve telefon alanları zorunludur.');
      return;
    }

    setSubmitting(true);
    setError(null);

    const orderRequest: CreateOrderRequest = {
      customerName: customerName.trim(),
      customerPhone: customerPhone.trim(),
      customerNote: customerNote.trim() || undefined,
      jewelryType,
      templateId: selectedTemplate?.id ?? 0,
      size: size.label,
      stoneSizeMm,
      items: filledSlots.map((s) => ({
        slotIndex: s.index,
        stoneId: s.stone!.id,
      })),
    };

    try {
      await createOrder(orderRequest);
      setSuccess(true);
    } catch {
      setError('Sipariş oluşturulurken bir hata oluştu. Lütfen tekrar deneyin.');
    } finally {
      setSubmitting(false);
    }
  }

  if (success) {
    return (
      <div
        className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
        data-testid="order-modal"
      >
        <div className="bg-gray-900 rounded-2xl p-6 w-full max-w-md mx-4 text-white text-center">
          <p className="text-lg font-semibold mb-2">Sipariş Başarıyla Oluşturuldu!</p>
          <p className="text-white/60 text-sm mb-4">Siparişiniz alınmıştır.</p>
          <button
            type="button"
            onClick={onClose}
            className="px-6 py-2 bg-purple-500 hover:bg-purple-600 rounded-lg text-sm font-semibold"
          >
            Tamam
          </button>
        </div>
      </div>
    );
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center bg-black/60"
      data-testid="order-modal"
    >
      <div className="bg-gray-900 rounded-2xl p-6 w-full max-w-lg mx-4 text-white max-h-[90vh] overflow-y-auto">
        <h2 className="text-lg font-semibold mb-4">Sipariş Özeti</h2>

        {/* Design details */}
        <div className="space-y-1 text-sm mb-4">
          <p>
            <span className="text-white/60">Tasarım Türü:</span>{' '}
            {typeLabels[jewelryType] ?? jewelryType}
          </p>
          <p>
            <span className="text-white/60">Model Şablonu:</span>{' '}
            {selectedTemplate?.name ?? '—'}
          </p>
          <p>
            <span className="text-white/60">Takı Ölçüsü:</span> {size.label}
          </p>
          <p>
            <span className="text-white/60">Taş Boyutu:</span> {stoneSizeMm}mm
          </p>
        </div>

        {/* Stone list */}
        <div className="mb-4">
          <p className="text-sm text-white/60 mb-2">
            Yerleştirilen Taşlar ({filledSlots.length})
          </p>
          <ul className="space-y-1 max-h-32 overflow-y-auto">
            {filledSlots.map((slot) => (
              <li
                key={slot.index}
                className="flex items-center gap-2 text-xs bg-white/10 rounded px-2 py-1"
              >
                {isColor(slot.stone!.image) ? (
                  <div
                    className="w-5 h-5 rounded-full shrink-0 border border-white/30"
                    style={{ backgroundColor: slot.stone!.image }}
                  />
                ) : (
                  <img
                    src={slot.stone!.image}
                    alt={slot.stone!.name}
                    className="w-5 h-5 rounded-full object-cover"
                  />
                )}
                <span>{slot.stone!.name}</span>
              </li>
            ))}
          </ul>
        </div>

        {/* Customer form */}
        <div className="space-y-3 mb-4">
          <div>
            <label htmlFor="customerName" className="block text-xs text-white/60 mb-1">
              Ad Soyad *
            </label>
            <input
              id="customerName"
              type="text"
              value={customerName}
              onChange={(e) => setCustomerName(e.target.value)}
              className="w-full bg-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-white/40 outline-none focus:ring-1 focus:ring-purple-400"
              placeholder="Adınız Soyadınız"
            />
          </div>
          <div>
            <label htmlFor="customerPhone" className="block text-xs text-white/60 mb-1">
              Telefon *
            </label>
            <input
              id="customerPhone"
              type="tel"
              value={customerPhone}
              onChange={(e) => setCustomerPhone(e.target.value)}
              className="w-full bg-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-white/40 outline-none focus:ring-1 focus:ring-purple-400"
              placeholder="05XX XXX XX XX"
            />
          </div>
          <div>
            <label htmlFor="customerNote" className="block text-xs text-white/60 mb-1">
              Not (opsiyonel)
            </label>
            <textarea
              id="customerNote"
              value={customerNote}
              onChange={(e) => setCustomerNote(e.target.value)}
              rows={2}
              className="w-full bg-white/10 rounded-lg px-3 py-2 text-sm text-white placeholder-white/40 outline-none focus:ring-1 focus:ring-purple-400 resize-none"
              placeholder="Eklemek istediğiniz not..."
            />
          </div>
        </div>

        {error && (
          <p className="text-red-400 text-xs mb-3" data-testid="order-error">
            {error}
          </p>
        )}

        {/* Actions */}
        <div className="flex gap-3">
          <button
            type="button"
            onClick={onClose}
            disabled={submitting}
            className="flex-1 py-2 rounded-lg text-sm font-semibold bg-white/10 hover:bg-white/20 transition-colors"
          >
            İptal
          </button>
          <button
            type="button"
            onClick={handleConfirm}
            disabled={submitting}
            className="flex-1 py-2 rounded-lg text-sm font-semibold bg-purple-500 hover:bg-purple-600 transition-colors disabled:opacity-50"
          >
            {submitting ? 'Gönderiliyor...' : 'Onayla'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default OrderModal;
