'use client'

import { useState } from'react'
import { X, AlertTriangle } from'lucide-react'
import { createClient } from'@/lib/supabase/client'
import { useToast } from'@/components/repository/toast'
import type { SupplierResult } from'@/components/ui/supplier-search'

// ─── Types ────────────────────────────────────────────────────────────────────

interface CreateSupplierInlineProps {
 open: boolean
 onClose: () => void
 onCreated: (supplier: SupplierResult) => void
 initialName?: string
}

interface SimilarSupplier {
 id: string
 supplier_name: string
 city: string | null
}

interface FormState {
 supplier_name: string
 supplier_number: string
 city: string
 country: string
 supplier_location: string
 plant: string
}

// ─── Constants ────────────────────────────────────────────────────────────────

const INPUT_CLS ='w-full h-11 px-3 rounded-lg border border-border bg-background text-sm focus:outline-none focus:ring-2 focus:ring-primary transition-colors'
const LABEL_CLS ='block text-sm font-medium text-foreground mb-1.5'
const DEFAULT_COUNTRY ='DE'

// ─── Component ────────────────────────────────────────────────────────────────

export default function CreateSupplierInline({
 open,
 onClose,
 onCreated,
 initialName ='',
}: CreateSupplierInlineProps) {
 const { toast } = useToast()

 const [form, setForm] = useState<FormState>({
 supplier_name: initialName,
 supplier_number:'',
 city:'',
 country: DEFAULT_COUNTRY,
 supplier_location:'',
 plant:'',
 })
 const [errors, setErrors] = useState<Partial<Record<keyof FormState, string>>>({})
 const [saving, setSaving] = useState(false)
 const [saveError, setSaveError] = useState('')
 const [similarWarning, setSimilarWarning] = useState<SimilarSupplier | null>(null)

 if (!open) return null

 function setField(key: keyof FormState, value: string) {
 setForm(f => ({ ...f, [key]: value }))
 if (errors[key]) setErrors(e => ({ ...e, [key]:''}))
 }

 // Lieferantennummer must follow the BMW supplier-number convention // allow-customer-string
 // documented by the operator: 6 digits, dash, 2 digits — e.g. "123456-10".
 const SUPPLIER_NUMBER_RE = /^\d{6}-\d{2}$/

 function validate(): boolean {
 const newErrors: Partial<Record<keyof FormState, string>> = {}
 if (!form.supplier_name.trim()) newErrors.supplier_name ='Pflichtfeld'
 const num = form.supplier_number.trim()
 if (!num) {
 newErrors.supplier_number ='Pflichtfeld'
 } else if (!SUPPLIER_NUMBER_RE.test(num)) {
 newErrors.supplier_number ='Format muss 123456-10 sein (6 Ziffern, Bindestrich, 2 Ziffern)'
 }
 setErrors(newErrors)
 return Object.keys(newErrors).length === 0
 }

 async function handleSubmit(e: React.FormEvent, forceCreate = false) {
 e.preventDefault()
 if (!validate()) return

 setSaving(true)
 setSaveError('')
 setSimilarWarning(null)

 try {
 const supabase = createClient()

 // 1. Check supplier_number uniqueness
 const { data: existing } = await supabase
 .from('supplier_master_data')
 .select('id, supplier_number')
 .eq('supplier_number', form.supplier_number.trim())
 .maybeSingle()

 if (existing) {
 setErrors(e => ({ ...e, supplier_number: `Lieferantennummer ${form.supplier_number.trim()} existiert bereits` }))
 setSaving(false)
 return
 }

 // 2. Similar name check (only on first submit, not when forced)
 if (!forceCreate) {
 const { data: similars } = await supabase
 .from('supplier_master_data')
 .select('id, supplier_name, city')
 .ilike('supplier_name', `%${form.supplier_name.trim()}%`)
 .eq('is_active', true)
 .limit(1)

 if (similars && similars.length > 0) {
 const s = similars[0] as SimilarSupplier
 // Only warn if city also matches or name is very similar
 const nameMatch = s.supplier_name.toLowerCase().includes(form.supplier_name.trim().toLowerCase().slice(0, 6))
 const cityMatch = form.city.trim() && s.city?.toLowerCase() === form.city.trim().toLowerCase()
 if (nameMatch && cityMatch) {
 setSimilarWarning(s)
 setSaving(false)
 return
 }
 }
 }

 // 3. Get current user
 const { data: { user } } = await supabase.auth.getUser()

 // 4. Insert supplier
 const { data: newSupplier, error } = await supabase
 .from('supplier_master_data')
 .insert({
 supplier_name: form.supplier_name.trim(),
 supplier_number: form.supplier_number.trim(),
 city: form.city.trim() || null,
 country: form.country.trim() || null,
 supplier_location: form.supplier_location.trim() || null,
 plant: form.plant.trim() || null,
 is_active: true,
 created_by: user?.id ?? null,
 })
 .select('id, supplier_number, supplier_name, city, country, supplier_location')
 .single()

 if (error || !newSupplier) {
 // Surface the failure both inline (form-level message) AND as a toast,
 // so the user does not silently believe the supplier was created when
 // RLS or a unique-constraint stopped the insert.
 const reason = error?.message ??'Unbekannter Fehler'
 const friendly = error?.code ==='42501'
 ?'Du hast keine Berechtigung, neue Lieferanten anzulegen. Bitte einen Admin oder Masteradmin.'
 : error?.code ==='23505'
 ?'Lieferantennummer ist bereits vergeben.'
 : reason
 setSaveError(friendly)
 toast({ message: friendly, type:'error'})
 setSaving(false)
 return
 }

 toast({ message:'Lieferant angelegt und ausgewählt', type:'success'})
 onCreated(newSupplier as SupplierResult)
 } catch {
 const msg = 'Ein unerwarteter Fehler ist aufgetreten'
 setSaveError(msg)
 toast({ message: msg, type: 'error' })
 setSaving(false)
 // Error surfaced to user via toast + saveError state.
 }
 }

 async function handleForceCreate() {
 setSimilarWarning(null)
 const fakeEvent = { preventDefault: () => {} } as React.FormEvent
 await handleSubmit(fakeEvent, true)
 }

 return (
 <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
 {/* Backdrop */}
 <div
 className="absolute inset-0 bg-black/40 backdrop-blur-sm"
 onClick={onClose}
 aria-hidden="true"
 />

 {/* Card */}
 <div className="relative bg-card rounded-xl border border-border w-full max-w-lg max-h-[90vh] overflow-y-auto">
 {/* Header */}
 <div className="flex items-center justify-between px-5 py-4 border-b border-border bg-background rounded-t-xl">
 <h2 className="text-sm font-semibold text-foreground">Neuen Lieferanten anlegen</h2>
 <button
 type="button"
 onClick={onClose}
 aria-label="Schließen"
 className="text-muted-foreground hover:text-foreground transition-colors"
 >
 <X size={18} />
 </button>
 </div>

 {/* Similar supplier warning */}
 {similarWarning && (
 <div className="mx-5 mt-4 p-4 rounded-lg border border-status-yellow/60 bg-[#FFFBEA] flex gap-3">
 <AlertTriangle size={16} className="text-[#B38600] shrink-0 mt-0.5"/>
 <div className="flex-1 min-w-0">
 <p className="text-sm font-medium text-foreground">Ähnlicher Lieferant gefunden</p>
 <p className="text-sm text-muted-foreground mt-0.5">
 {similarWarning.supplier_name}{similarWarning.city ? `, ${similarWarning.city}` :''}
 </p>
 <div className="flex gap-2 mt-3">
 <button
 type="button"
 onClick={() => setSimilarWarning(null)}
 className="h-8 px-3 rounded-lg border border-border text-sm text-foreground hover:bg-background transition-colors"
 >
 Abbrechen
 </button>
 <button
 type="button"
 onClick={handleForceCreate}
 className="h-8 px-3 rounded-lg bg-primary text-white text-sm hover:bg-primary-dark transition-colors"
 >
 Trotzdem anlegen
 </button>
 </div>
 </div>
 </div>
 )}

 <form onSubmit={handleSubmit} className="p-5 space-y-4">
 {/* Lieferantenname */}
 <div>
 <label className={LABEL_CLS}>
 Lieferantenname <span className="text-destructive">*</span>
 </label>
 <input
 type="text"
 value={form.supplier_name}
 onChange={e => setField('supplier_name', e.target.value)}
 className={`${INPUT_CLS} ${errors.supplier_name ?'border-destructive':''}`}
 placeholder="z.B. Bosch Rexroth AG"
 />
 {errors.supplier_name && (
 <p className="mt-1 text-xs text-destructive">{errors.supplier_name}</p>
 )}
 </div>

 {/* Lieferantennummer */}
 <div>
 <label className={LABEL_CLS}>
 Lieferantennummer <span className="text-destructive">*</span>
 </label>
 <input
 type="text"
 value={form.supplier_number}
 onChange={e => setField('supplier_number', e.target.value)}
 className={`${INPUT_CLS} ${errors.supplier_number ?'border-destructive':''}`}
 placeholder="z.B. 123456-10"
 pattern="\d{6}-\d{2}"
 inputMode="numeric"
 title="6 Ziffern, Bindestrich, 2 Ziffern (z.B. 123456-10)"
 />
 {errors.supplier_number && (
 <p className="mt-1 text-xs text-destructive">{errors.supplier_number}</p>
 )}
 </div>

 {/* Stadt & Land */}
 <div className="grid grid-cols-2 gap-4">
 <div>
 <label className={LABEL_CLS}>Stadt</label>
 <input
 type="text"
 value={form.city}
 onChange={e => setField('city', e.target.value)}
 className={INPUT_CLS}
 placeholder="z.B. München"
 />
 </div>
 <div>
 <label className={LABEL_CLS}>Land</label>
 <input
 type="text"
 value={form.country}
 onChange={e => setField('country', e.target.value)}
 className={INPUT_CLS}
 placeholder="z.B. DE"
 />
 </div>
 </div>

 {/* Standort & Werk */}
 <div className="grid grid-cols-2 gap-4">
 <div>
 <label className={LABEL_CLS}>Standort</label>
 <input
 type="text"
 value={form.supplier_location}
 onChange={e => setField('supplier_location', e.target.value)}
 className={INPUT_CLS}
 placeholder="Optional"
 />
 </div>
 <div>
 <label className={LABEL_CLS}>Werk</label>
 <input
 type="text"
 value={form.plant}
 onChange={e => setField('plant', e.target.value)}
 className={INPUT_CLS}
 placeholder="Optional"
 />
 </div>
 </div>

 {/* Save error */}
 {saveError && (
 <p className="text-sm text-destructive">{saveError}</p>
 )}

 {/* Actions */}
 <div className="flex justify-end gap-3 pt-2">
 <button
 type="button"
 onClick={onClose}
 className="h-11 px-4 rounded-lg border border-border text-sm text-foreground hover:bg-background transition-colors"
 >
 Abbrechen
 </button>
 <button
 type="submit"
 disabled={saving}
 className="h-11 px-5 rounded-lg bg-primary text-white text-sm font-medium hover:bg-primary-dark transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
 >
 {saving ?'Anlegen…':'Lieferant anlegen'}
 </button>
 </div>
 </form>
 </div>
 </div>
 )
}
