"use client"

import React, { useState } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { 
  ShoppingCart,
  Users,
  ArrowLeft,
  Package,
  Building2,
  MapPin,
  Phone,
  Mail,
  Star
} from 'lucide-react'
import { WBProductCards } from './wb-product-cards'
// import { WholesalerSelection } from './wholesaler-selection'

interface Wholesaler {
  id: string
  inn: string
  name: string
  fullName: string
  address: string
  phone?: string
  email?: string
  rating: number
  productCount: number
  avatar?: string
  specialization: string[]
}

interface WildberriesCard {
  nmID: number
  vendorCode: string
  title: string
  description: string
  brand: string
  mediaFiles: string[]
  sizes: Array<{
    chrtID: number
    techSize: string
    wbSize: string
    price: number
    discountedPrice: number
    quantity: number
  }>
}

interface SelectedCard {
  card: WildberriesCard
  selectedQuantity: number
  selectedMarket: string
  selectedPlace: string
  sellerName: string
  sellerPhone: string
  deliveryDate: string
  selectedServices: string[]
}

interface CreateSupplyFormProps {
  onClose: () => void
  onSupplyCreated: () => void
}

// Моковые данные оптовиков
const mockWholesalers: Wholesaler[] = [
  {
    id: '1',
    inn: '7707083893',
    name: 'ОПТ-Электроника',
    fullName: 'ООО "ОПТ-Электроника"',
    address: 'г. Москва, ул. Садовая, д. 15',
    phone: '+7 (495) 123-45-67',
    email: 'opt@electronics.ru',
    rating: 4.8,
    productCount: 1250,
    specialization: ['Электроника', 'Бытовая техника']
  },
  {
    id: '2',
    inn: '7707083894',
    name: 'ТекстильМастер',
    fullName: 'ООО "ТекстильМастер"',
    address: 'г. Иваново, пр. Ленина, д. 42',
    phone: '+7 (4932) 55-66-77',
    email: 'sales@textilmaster.ru',
    rating: 4.6,
    productCount: 850,
    specialization: ['Текстиль', 'Одежда', 'Домашний текстиль']
  },
  {
    id: '3',
    inn: '7707083895',
    name: 'МетизКомплект',
    fullName: 'ООО "МетизКомплект"',
    address: 'г. Тула, ул. Металлургов, д. 8',
    phone: '+7 (4872) 33-44-55',
    email: 'info@metiz.ru',
    rating: 4.9,
    productCount: 2100,
    specialization: ['Крепеж', 'Метизы', 'Инструменты']
  }
]

export function CreateSupplyForm({ onClose, onSupplyCreated }: CreateSupplyFormProps) {
  const [selectedVariant, setSelectedVariant] = useState<'cards' | 'wholesaler' | null>(null)
  const [selectedWholesaler, setSelectedWholesaler] = useState<Wholesaler | null>(null)
  const [selectedCards, setSelectedCards] = useState<SelectedCard[]>([])

  const renderStars = (rating: number) => {
    return Array.from({ length: 5 }, (_, i) => (
      <Star 
        key={i} 
        className={`h-4 w-4 ${i < Math.floor(rating) ? 'text-yellow-400 fill-current' : 'text-gray-400'}`} 
      />
    ))
  }

  const handleCardsComplete = (cards: SelectedCard[]) => {
    setSelectedCards(cards)
    console.log('Карточки товаров выбраны:', cards)
    // TODO: Здесь будет создание поставки с данными карточек
    onSupplyCreated()
  }

  if (selectedVariant === 'cards') {
    return (
      <WBProductCards 
        onBack={() => setSelectedVariant(null)}
        onComplete={handleCardsComplete}
      />
    )
  }

  if (selectedVariant === 'wholesaler') {
    if (selectedWholesaler) {
      return (
        <div className="space-y-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-3">
              <Button 
                variant="ghost" 
                size="sm"
                onClick={() => setSelectedWholesaler(null)}
                className="text-white/60 hover:text-white hover:bg-white/10"
              >
                <ArrowLeft className="h-4 w-4 mr-2" />
                Назад
              </Button>
              <div>
                <h2 className="text-2xl font-bold text-white mb-1">Товары оптовика</h2>
                <p className="text-white/60">{selectedWholesaler.name}</p>
              </div>
            </div>
            <Button 
              variant="ghost" 
              size="sm"
              onClick={onClose}
              className="text-white/60 hover:text-white hover:bg-white/10"
            >
              Отмена
            </Button>
          </div>
          <div className="text-center py-12">
            <p className="text-white/60">Компонент товаров оптовика в разработке...</p>
          </div>
        </div>
      )
    }

    return (
      <div className="space-y-6">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-3">
            <Button 
              variant="ghost" 
              size="sm"
              onClick={() => setSelectedVariant(null)}
              className="text-white/60 hover:text-white hover:bg-white/10"
            >
              <ArrowLeft className="h-4 w-4 mr-2" />
              Назад
            </Button>
            <div>
              <h2 className="text-2xl font-bold text-white mb-1">Выбор оптовика</h2>
              <p className="text-white/60">Выберите оптовика для создания поставки</p>
            </div>
          </div>
          <Button 
            variant="ghost" 
            size="sm"
            onClick={onClose}
            className="text-white/60 hover:text-white hover:bg-white/10"
          >
            Отмена
          </Button>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {mockWholesalers.map((wholesaler) => (
            <Card 
              key={wholesaler.id}
              className="bg-white/10 backdrop-blur border-white/20 p-6 cursor-pointer transition-all hover:bg-white/15 hover:border-white/30 hover:scale-105"
              onClick={() => setSelectedWholesaler(wholesaler)}
            >
              <div className="space-y-4">
                {/* Заголовок карточки */}
                <div className="flex items-start space-x-3">
                  <div className="p-3 bg-blue-500/20 rounded-lg">
                    <Building2 className="h-6 w-6 text-blue-400" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <h3 className="text-white font-semibold text-lg mb-1 truncate">
                      {wholesaler.name}
                    </h3>
                    <p className="text-white/60 text-xs mb-2 truncate">
                      {wholesaler.fullName}
                    </p>
                    <div className="flex items-center space-x-1 mb-2">
                      {renderStars(wholesaler.rating)}
                      <span className="text-white/60 text-sm ml-2">{wholesaler.rating}</span>
                    </div>
                  </div>
                </div>

                {/* Информация */}
                <div className="space-y-2">
                  <div className="flex items-center space-x-2">
                    <MapPin className="h-4 w-4 text-gray-400" />
                    <span className="text-white/80 text-sm truncate">{wholesaler.address}</span>
                  </div>
                  
                  {wholesaler.phone && (
                    <div className="flex items-center space-x-2">
                      <Phone className="h-4 w-4 text-gray-400" />
                      <span className="text-white/80 text-sm">{wholesaler.phone}</span>
                    </div>
                  )}

                  {wholesaler.email && (
                    <div className="flex items-center space-x-2">
                      <Mail className="h-4 w-4 text-gray-400" />
                      <span className="text-white/80 text-sm truncate">{wholesaler.email}</span>
                    </div>
                  )}

                  <div className="flex items-center space-x-2">
                    <Package className="h-4 w-4 text-gray-400" />
                    <span className="text-white/80 text-sm">{wholesaler.productCount} товаров</span>
                  </div>
                </div>

                {/* Специализация */}
                <div className="space-y-2">
                  <p className="text-white/60 text-xs">Специализация:</p>
                  <div className="flex flex-wrap gap-1">
                    {wholesaler.specialization.map((spec, index) => (
                      <Badge 
                        key={index}
                        className="bg-purple-500/20 text-purple-300 border-purple-500/30 text-xs"
                      >
                        {spec}
                      </Badge>
                    ))}
                  </div>
                </div>

                {/* ИНН */}
                <div className="pt-2 border-t border-white/10">
                  <p className="text-white/60 text-xs">ИНН: {wholesaler.inn}</p>
                </div>
              </div>
            </Card>
          ))}
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-white mb-2">Создание поставки</h2>
          <p className="text-white/60">Выберите способ создания поставки</p>
        </div>
        <Button 
          variant="ghost" 
          size="sm"
          onClick={onClose}
          className="text-white/60 hover:text-white hover:bg-white/10"
        >
          Отмена
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Вариант 1: Карточки */}
        <Card 
          className="bg-white/10 backdrop-blur border-white/20 p-6 cursor-pointer transition-all hover:bg-white/15 hover:border-white/30"
          onClick={() => setSelectedVariant('cards')}
        >
          <div className="text-center space-y-4">
            <div className="p-4 bg-blue-500/20 rounded-lg w-fit mx-auto">
              <ShoppingCart className="h-8 w-8 text-blue-400" />
            </div>
            <div>
              <h3 className="text-xl font-semibold text-white mb-2">Карточки</h3>
              <p className="text-white/60 text-sm">
                Создание поставки через выбор товаров по карточкам
              </p>
            </div>
            <Badge className="bg-green-500/20 text-green-300 border-green-500/30">
              Доступно
            </Badge>
          </div>
        </Card>

        {/* Вариант 2: Оптовик */}
        <Card 
          className="bg-white/10 backdrop-blur border-white/20 p-6 cursor-pointer transition-all hover:bg-white/15 hover:border-white/30"
          onClick={() => setSelectedVariant('wholesaler')}
        >
          <div className="text-center space-y-4">
            <div className="p-4 bg-green-500/20 rounded-lg w-fit mx-auto">
              <Users className="h-8 w-8 text-green-400" />
            </div>
            <div>
              <h3 className="text-xl font-semibold text-white mb-2">Оптовик</h3>
              <p className="text-white/60 text-sm">
                Создание поставки через выбор товаров у оптовиков
              </p>
            </div>
            <Badge className="bg-green-500/20 text-green-300 border-green-500/30">
              Доступно
            </Badge>
          </div>
        </Card>
      </div>


    </div>
  )
} 