/**
 * БЛОК КОНФИГУРАЦИИ УСЛУГ И НАСТРОЕК
 *
 * Выделен из direct-supply-creation.tsx
 * Управляет выбором фулфилмента, услуг, расходников и датой поставки
 */

'use client'

import { format } from 'date-fns'
import { ru } from 'date-fns/locale'
import { Calendar as CalendarIcon, Truck, Building } from 'lucide-react'
import React from 'react'
import DatePicker from 'react-datepicker'

import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'

import 'react-datepicker/dist/react-datepicker.css'

import type { ServicesConfigBlockProps, Organization } from '../types/direct-supply.types'

export const ServicesConfigBlock = React.memo(function ServicesConfigBlock({
  selectedFulfillmentId: _selectedFulfillmentId,
  selectedServices,
  selectedConsumables,
  organizationServices,
  organizationSupplies,
  deliveryDateOriginal,
  selectedFulfillmentOrg,
  counterpartiesData,
  onServiceToggle,
  onConsumableToggle,
  onDeliveryDateChange,
  onFulfillmentChange,
}: ServicesConfigBlockProps) {
  const fulfillmentOrgs = (counterpartiesData?.myCounterparties || []).filter(
    (org: Organization) => org.type === 'FULFILLMENT',
  )

  return (
    <Card className="bg-white/10 backdrop-blur border-white/20 p-4">
      <div className="flex items-center space-x-3 mb-4">
        <div className="w-8 h-8 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-lg flex items-center justify-center">
          <Truck className="h-4 w-4 text-white" />
        </div>
        <div>
          <h3 className="text-white font-semibold text-base">Настройки поставки</h3>
          <p className="text-white/60 text-xs">Фулфилмент, услуги и дата</p>
        </div>
      </div>

      <div className="space-y-4">
        {/* Выбор фулфилмента и дата поставки */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Фулфилмент центр */}
          <div>
            <label className="text-white/80 text-sm mb-2 block">
              <Building className="h-4 w-4 inline mr-2" />
              Фулфилмент центр
            </label>
            <Select value={selectedFulfillmentOrg} onValueChange={onFulfillmentChange}>
              <SelectTrigger className="bg-white/10 border-white/20 text-white">
                <SelectValue placeholder="Выберите фулфилмент" />
              </SelectTrigger>
              <SelectContent>
                {fulfillmentOrgs.map((org: Organization) => (
                  <SelectItem key={org.id} value={org.id}>
                    {org.name || org.fullName}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Дата поставки */}
          <div>
            <label className="text-white/80 text-sm mb-2 block">
              <CalendarIcon className="h-4 w-4 inline mr-2" />
              Дата поставки
            </label>
            <div className="relative">
              <DatePicker
                selected={deliveryDateOriginal}
                onChange={onDeliveryDateChange}
                minDate={new Date()}
                dateFormat="dd.MM.yyyy"
                locale={ru}
                className="w-full h-10 px-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:bg-white/15 focus:border-white/40"
                placeholderText="Выберите дату"
                customInput={
                  <Button
                    variant="outline"
                    className="w-full justify-start bg-white/10 border-white/20 text-white hover:bg-white/15"
                  >
                    <CalendarIcon className="h-4 w-4 mr-2" />
                    {deliveryDateOriginal
                      ? format(deliveryDateOriginal, 'dd.MM.yyyy', { locale: ru })
                      : 'Выберите дату'}
                  </Button>
                }
              />
            </div>
          </div>
        </div>

        {/* Услуги и расходники */}
        {selectedFulfillmentOrg && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Услуги фулфилмента */}
            <div>
              <label className="text-white/80 text-sm mb-2 block">Услуги фулфилмента</label>
              <div className="bg-white/5 rounded-lg p-3 max-h-40 overflow-y-auto">
                {organizationServices[selectedFulfillmentOrg] ? (
                  <div className="space-y-2">
                    {organizationServices[selectedFulfillmentOrg].map((service) => (
                      <label
                        key={service.id}
                        className="flex items-center space-x-2 cursor-pointer hover:bg-white/5 rounded p-1 transition-colors"
                      >
                        <input
                          type="checkbox"
                          checked={selectedServices.includes(service.id)}
                          onChange={() => onServiceToggle(service.id)}
                          className="w-4 h-4 rounded text-blue-500"
                        />
                        <div className="flex-1 min-w-0">
                          <div className="text-white text-sm font-medium">{service.name}</div>
                          <div className="text-emerald-400 text-xs">{service.price}₽</div>
                          {service.description && <div className="text-white/50 text-xs">{service.description}</div>}
                        </div>
                      </label>
                    ))}
                  </div>
                ) : (
                  <div className="text-white/60 text-sm py-4 text-center">
                    <div className="animate-spin w-4 h-4 border-2 border-white/20 border-t-white/60 rounded-full mx-auto mb-2"></div>
                    Загрузка услуг...
                  </div>
                )}
              </div>
              {selectedServices.length > 0 && (
                <div className="mt-2 text-xs text-white/60">Выбрано услуг: {selectedServices.length}</div>
              )}
            </div>

            {/* Расходные материалы */}
            <div>
              <label className="text-white/80 text-sm mb-2 block">Расходные материалы</label>
              <div className="bg-white/5 rounded-lg p-3 max-h-40 overflow-y-auto">
                {organizationSupplies[selectedFulfillmentOrg] ? (
                  <div className="space-y-2">
                    {organizationSupplies[selectedFulfillmentOrg].map((supply) => (
                      <label
                        key={supply.id}
                        className="flex items-center space-x-2 cursor-pointer hover:bg-white/5 rounded p-1 transition-colors"
                      >
                        <input
                          type="checkbox"
                          checked={selectedConsumables.includes(supply.id)}
                          onChange={() => onConsumableToggle(supply.id)}
                          className="w-4 h-4 rounded text-purple-500"
                        />
                        <div className="flex-1 min-w-0">
                          <div className="text-white text-sm font-medium">{supply.name}</div>
                          <div className="text-purple-400 text-xs">{supply.price}₽</div>
                          {supply.description && <div className="text-white/50 text-xs">{supply.description}</div>}
                        </div>
                      </label>
                    ))}
                  </div>
                ) : (
                  <div className="text-white/60 text-sm py-4 text-center">
                    <div className="animate-spin w-4 h-4 border-2 border-white/20 border-t-white/60 rounded-full mx-auto mb-2"></div>
                    Загрузка расходников...
                  </div>
                )}
              </div>
              {selectedConsumables.length > 0 && (
                <div className="mt-2 text-xs text-white/60">Выбрано расходников: {selectedConsumables.length}</div>
              )}
            </div>
          </div>
        )}

        {/* Информационная панель */}
        {!selectedFulfillmentOrg && (
          <div className="bg-blue-500/10 border border-blue-400/30 rounded-lg p-3">
            <p className="text-blue-300 text-sm">
              💡 <strong>Подсказка:</strong> Выберите фулфилмент центр для настройки услуг и расходников
            </p>
          </div>
        )}
      </div>
    </Card>
  )
})
