'use client'

import React from 'react'
import { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { User, Building2, UserPlus, Search, Check, Loader2, ChevronRight } from 'lucide-react'
import { EndCustomer, Profile } from '@/lib/types'

interface StepCustomerProps {
  isAdmin: boolean
  companies: any[]
  selectedCompanyId: string | null
  setSelectedCompanyId: (id: string | null) => void
  customerMode: 'select' | 'create'
  setCustomerMode: (mode: 'select' | 'create') => void
  endCustomers: EndCustomer[]
  searchTerm: string
  setSearchTerm: (term: string) => void
  filteredEndCustomers: EndCustomer[]
  selectedEndCustomerId: string | null
  setSelectedEndCustomerId: (id: string | null) => void
  newCustomerForm: any
  setNewCustomerForm: React.Dispatch<React.SetStateAction<any>>
  handleCreateCustomer: () => Promise<void>
  isCreatingCustomer: boolean
  nextStep: () => void
}

export function StepCustomer({
  isAdmin,
  companies,
  selectedCompanyId,
  setSelectedCompanyId,
  customerMode,
  setCustomerMode,
  endCustomers,
  searchTerm,
  setSearchTerm,
  filteredEndCustomers,
  selectedEndCustomerId,
  setSelectedEndCustomerId,
  newCustomerForm,
  setNewCustomerForm,
  handleCreateCustomer,
  isCreatingCustomer,
  nextStep,
}: StepCustomerProps) {
  return (
    <Card className="glass-dark border-white/10">
      <CardHeader>
        <CardTitle className="text-2xl flex items-center gap-2 text-white">
          <User className="w-6 h-6 text-primary" />
          Für wen bestellen Sie?
        </CardTitle>
        <CardDescription className="text-slate-300">
          Wählen Sie einen Endkunden aus oder legen Sie einen neuen an.
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-6">
        {/* Admin Company Selector */}
        {isAdmin && (
          <div className="p-4 rounded-xl bg-white/5 border border-white/10 space-y-3">
            <Label htmlFor="order-company" className="text-white font-medium flex items-center gap-2">
              <Building2 className="w-4 h-4 text-primary" />
              Zugeordnetes Unternehmen (Admin-Option)
            </Label>
            <select
              id="order-company"
              value={selectedCompanyId || ''}
              onChange={(e) => setSelectedCompanyId(e.target.value || null)}
              className="flex h-9 w-full rounded-md border border-white/10 bg-slate-900 px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary text-white"
            >
              <option value="">Keine Firma zugewiesen</option>
              {companies.map((c: any) => (
                <option key={c.id} value={c.id}>
                  {c.name}
                </option>
              ))}
            </select>
          </div>
        )}

        {/* Modus-Toggle */}
        <div className="flex gap-2">
          <Button
            variant={customerMode === 'select' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setCustomerMode('select')}
            className={`gap-2 ${customerMode === 'select' ? '' : 'text-white'}`}
          >
            <Building2 className="w-4 h-4" /> Bestandskunde wählen
          </Button>
          <Button
            variant={customerMode === 'create' ? 'default' : 'ghost'}
            size="sm"
            onClick={() => setCustomerMode('create')}
            className={`gap-2 ${customerMode === 'create' ? '' : 'text-white'}`}
          >
            <UserPlus className="w-4 h-4" /> Neuen Kunden anlegen
          </Button>
        </div>

        {/* Modus A: Bestandskunde wählen */}
        {customerMode === 'select' && (
          <div className="space-y-4">
            {endCustomers.filter(c => !c.is_anonymized).length === 0 ? (
              <div className="p-6 rounded-xl bg-white/5 border border-white/10 text-center space-y-3">
                <Building2 className="w-10 h-10 text-slate-600 mx-auto" />
                <p className="text-slate-400">Noch keine Endkunden angelegt.</p>
                <Button variant="outline" size="sm" onClick={() => setCustomerMode('create')} className="border-white/10 text-white">
                  <UserPlus className="w-4 h-4 mr-2" /> Ersten Kunden anlegen
                </Button>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
                  <Input
                    placeholder="Kunden suchen nach Name, Ort, PLZ..."
                    value={searchTerm}
                    onChange={e => setSearchTerm(e.target.value)}
                    className="pl-9 bg-white/5 border-white/10 text-white placeholder:text-slate-500"
                  />
                </div>
                {filteredEndCustomers.length === 0 ? (
                  <div className="p-6 rounded-xl bg-white/5 border border-white/10 text-center">
                    <p className="text-slate-400">Keine passenden Kunden gefunden.</p>
                  </div>
                ) : (
                  <div className="space-y-2 max-h-72 overflow-y-auto pr-1">
                    {filteredEndCustomers.map(customer => (
                      <label
                        key={customer.id}
                        className={`flex items-start p-4 rounded-xl border-2 cursor-pointer transition-all ${selectedEndCustomerId === customer.id
                          ? 'border-primary bg-primary/5'
                          : 'border-white/5 bg-white/5 hover:bg-white/10'
                          }`}
                      >
                        <input
                          type="radio"
                          name="end_customer"
                          value={customer.id}
                          checked={selectedEndCustomerId === customer.id}
                          onChange={() => setSelectedEndCustomerId(customer.id)}
                          className="sr-only"
                        />
                        <div className="flex-1">
                          <p className="font-semibold text-white">{customer.company_name}</p>
                          <p className="text-sm text-slate-400">
                            {[customer.first_name, customer.last_name].filter(Boolean).join(' ')}
                            {customer.first_name || customer.last_name ? ' · ' : ''}
                            {[customer.street, customer.zip, customer.city].filter(Boolean).join(', ')}
                          </p>
                        </div>
                        {selectedEndCustomerId === customer.id && (
                          <Check className="w-5 h-5 text-primary mt-0.5 shrink-0" />
                        )}
                      </label>
                    ))}
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Modus B: Neuen Kunden anlegen */}
        {customerMode === 'create' && (
          <div className="grid md:grid-cols-2 gap-4 p-4 rounded-xl bg-white/5 border border-white/10">
            {([
              { label: 'Firmenname *', key: 'company_name', span: true, placeholder: 'GmbH / Einzelunternehmen' },
              { label: 'USt-IdNr.', key: 'vat_id', span: false, placeholder: 'DE123456789' },
              { label: 'Vorname', key: 'first_name', span: false, placeholder: '' },
              { label: 'Nachname', key: 'last_name', span: false, placeholder: '' },
              { label: 'Straße & Hausnummer', key: 'street', span: true, placeholder: '' },
              { label: 'PLZ', key: 'zip', span: false, placeholder: '' },
              { label: 'Ort', key: 'city', span: false, placeholder: '' },
              { label: 'Kontoinhaber', key: 'bank_owner', span: false, placeholder: 'Max Mustermann' },
              { label: 'IBAN', key: 'bank_iban', span: false, placeholder: 'DE89370400440532013000' },
              { label: 'BIC', key: 'bank_bic', span: false, placeholder: 'SOLADE21XXX' },
              { label: 'Bankname', key: 'bank_name', span: false, placeholder: 'Musterbank' },
            ] as const).map(({ label, key, span, placeholder }) => (
              <div key={key} className={`space-y-1.5 ${span ? 'md:col-span-2' : ''}`}>
                <Label className="text-slate-300 text-sm">{label}</Label>
                <Input
                  value={newCustomerForm[key] || ''}
                  onChange={e => setNewCustomerForm((prev: any) => ({ ...prev, [key]: e.target.value }))}
                  placeholder={placeholder}
                  className="bg-white/5 border-white/10 text-white placeholder:text-slate-500"
                />
              </div>
            ))}
            <div className="md:col-span-2 flex gap-2">
              <Button
                onClick={handleCreateCustomer}
                disabled={isCreatingCustomer || !newCustomerForm.company_name?.trim()}
                className="gap-2"
              >
                {isCreatingCustomer ? <Loader2 className="w-4 h-4 animate-spin" /> : <UserPlus className="w-4 h-4" />}
                Kunden speichern & auswählen
              </Button>
              <Button variant="ghost" className="text-white" onClick={() => setCustomerMode('select')}>
                Abbrechen
              </Button>
            </div>
          </div>
        )}
      </CardContent>
      <CardFooter className="flex justify-end border-t border-white/10 pt-6">
        <Button
          onClick={nextStep}
          disabled={
            customerMode === 'create' ||
            (customerMode === 'select' && endCustomers.filter(c => !c.is_anonymized).length > 0 && !selectedEndCustomerId)
          }
        >
          Weiter zum Abrechnungsmodell <ChevronRight className="ml-2 w-4 h-4" />
        </Button>
      </CardFooter>
    </Card>
  )
}
