'use client'

import { useState, useMemo } from'react'
import { createClient } from'@/lib/supabase/client'
import { Plus, Pencil, Trash2, X, GripVertical, Lock } from'lucide-react'
import type { AppointmentType } from'@/lib/planning-types'
import type { PlanningPerms } from'@/lib/planning-permissions'

interface Props {
 initialTypes: AppointmentType[]
 perms: PlanningPerms
}

type TypeForm = Omit<AppointmentType,'id'>

const EMPTY: TypeForm = {
 code:'',
 label:'',
 color:'var(--primary)',
 sort_order: 0,
}

const inputCls ='w-full h-8 rounded border border-muted text-[13px] text-foreground px-2 bg-card focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary'
const labelCls ='block text-[12px] font-medium text-foreground mb-1'

export default function SettingsClient({ initialTypes, perms }: Props) {
 const [types, setTypes] = useState<AppointmentType[]>(initialTypes)
 const [modal, setModal] = useState<{ mode:'create'|'edit'; data: TypeForm; id?: string } | null>(null)
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState<string | null>(null)
 const [confirmDelete, setConfirmDelete] = useState<string | null>(null)

 const canManage = perms.canManageMasterData
 const supabase = useMemo(() => createClient(), [])

 async function refresh() {
 const { data } = await supabase.from('appointment_types').select('*').order('sort_order')
 if (data) setTypes(data as AppointmentType[])
 }

 function openCreate() {
 const maxOrder = Math.max(0, ...types.map((t) => t.sort_order))
 setModal({ mode:'create', data: { ...EMPTY, sort_order: maxOrder + 1 } })
 setError(null)
 }

 function openEdit(t: AppointmentType) {
 const { id, ...rest } = t
 setModal({ mode:'edit', data: { ...rest }, id })
 setError(null)
 }

 function updateField<K extends keyof TypeForm>(key: K, val: TypeForm[K]) {
 if (!modal) return
 setModal({ ...modal, data: { ...modal.data, [key]: val } })
 }

 async function handleSave() {
 if (!modal) return
 setSaving(true)
 setError(null)

 let err
 if (modal.mode ==='create') {
 ;({ error: err } = await supabase.from('appointment_types').insert(modal.data))
 } else {
 ;({ error: err } = await supabase.from('appointment_types').update(modal.data).eq('id', modal.id!))
 }

 if (err) { setError(err.message); setSaving(false); return }
 await refresh()
 setModal(null)
 setSaving(false)
 }

 async function handleDelete(id: string) {
 const { error: err } = await supabase.from('appointment_types').delete().eq('id', id)
 if (err) { setError(err.message); return }
 setConfirmDelete(null)
 await refresh()
 }

 return (
 <div className="space-y-6">

 {/* Appointment Types */}
 <div className="bg-card rounded-xl border border-muted overflow-hidden mb-6">
 <div className="flex items-center justify-between px-5 py-3 border-b border-border">
 <div>
 <h2 className="font-semibold text-[14px] text-foreground">Auftragsarten</h2>
 <p className="text-[11px] text-muted-foreground">Farben und Bezeichnungen für Einsatztypen</p>
 </div>
 {canManage && (
 <button
 onClick={openCreate}
 className="h-8 px-3 flex items-center gap-1.5 text-[13px] font-medium rounded bg-primary text-white hover:bg-primary-dark transition-colors"
 >
 <Plus size={13} />
 Neu
 </button>
 )}
 </div>

 <div className="divide-y divide-muted">
 {types.length === 0 && (
 <p className="px-5 py-4 text-[12px] text-muted-foreground italic">Noch keine Auftragsarten definiert.</p>
 )}
 {types.map((t) => (
 <div key={t.id} className="flex items-center gap-3 px-5 py-2.5">
 {canManage && <GripVertical size={14} className="text-[#CCCCCC] cursor-grab shrink-0"/>}
 <span
 className="w-5 h-5 rounded border border-black/10 shrink-0"
 style={{ backgroundColor: t.color }}
 />
 <div className="flex-1 min-w-0">
 <p className="font-medium text-[13px] text-foreground">{t.label}</p>
 <p className="text-[11px] text-muted-foreground font-mono">{t.code}</p>
 </div>
 <span className="text-[11px] text-muted-foreground font-mono">{t.color}</span>
 <span className="text-[11px] text-[#CCCCCC] w-6 text-right">{t.sort_order}</span>
 {canManage && (
 <div className="flex gap-1 shrink-0">
 <button
 onClick={() => openEdit(t)}
 className="w-7 h-7 flex items-center justify-center rounded hover:bg-muted text-muted-foreground"
 >
 <Pencil size={13} />
 </button>
 {confirmDelete === t.id ? (
 <div className="flex items-center gap-1">
 <button
 onClick={() => handleDelete(t.id)}
 className="h-7 px-2 text-[11px] rounded bg-destructive text-white hover:bg-destructive"
 >
 Löschen
 </button>
 <button
 onClick={() => setConfirmDelete(null)}
 className="h-7 px-2 text-[11px] rounded border border-muted text-foreground hover:bg-muted"
 >
 Nein
 </button>
 </div>
 ) : (
 <button
 onClick={() => setConfirmDelete(t.id)}
 className="w-7 h-7 flex items-center justify-center rounded hover:bg-status-red-soft text-destructive"
 >
 <Trash2 size={13} />
 </button>
 )}
 </div>
 )}
 {!canManage && <Lock size={12} className="text-[#CCCCCC] shrink-0"/>}
 </div>
 ))}
 </div>
 </div>

 {/* Permissions info box */}
 <div className="bg-card rounded-xl border border-muted p-5">
 <h2 className="font-semibold text-[14px] text-foreground mb-3">Berechtigungen</h2>
 <div className="space-y-2 text-[12px]">
 {[
 { role:'admin', label:'Admin', desc:'Vollzugriff: alle CRUD-Operationen, Stammdaten, alle Mitarbeiter'},
 { role:'team_lead', label:'Team Lead', desc:'CRUD für alle Team-Einsätze, Berichte anzeigen, keine Stammdaten'},
 { role:'consultant', label:'Consultant', desc:'Nur eigene Einsätze bearbeiten, Team-Kalender lesen'},
 { role:'readonly', label:'Nur lesen', desc:'Nur Ansicht, keine Änderungen möglich'},
 ].map((r) => (
 <div key={r.role} className="flex items-start gap-3">
 <span className={`shrink-0 mt-0.5 px-2 py-0.5 rounded text-[11px] font-medium w-24 text-center ${
 r.role ==='admin'?'bg-status-red-soft text-destructive':
 r.role ==='team_lead'?'bg-secondary text-primary-dark':
 r.role ==='readonly'?'bg-muted text-muted-foreground':
'bg-[#F0F7FF] text-primary'
 }`}>
 {r.label}
 </span>
 <span className="text-[#555555]">{r.desc}</span>
 </div>
 ))}
 </div>
 <div className="mt-4 pt-3 border-t border-muted">
 <p className="text-[12px] text-muted-foreground">
 Deine aktuelle Rolle:{''}
 <span className="font-medium text-foreground">
 {perms.role ==='admin'?'Admin': perms.role ==='team_lead'?'Team Lead': perms.role ==='readonly'?'Nur lesen':'Consultant'}
 </span>
 {!perms.canManageMasterData && (
 <span className="ml-2 text-muted-foreground">(Stammdaten sind schreibgeschützt)</span>
 )}
 </p>
 </div>
 </div>

 {error && (
 <p className="mt-3 text-[12px] text-destructive bg-status-red-soft border border-status-red-strong rounded px-3 py-2">
 {error}
 </p>
 )}

 {/* Modal */}
 {modal && (
 <div
 className="fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4"
 onClick={(e) => e.target === e.currentTarget && setModal(null)}
 >
 <div className="bg-card text-foreground rounded-xl w-full max-w-sm flex flex-col">
 <div className="flex items-center justify-between px-5 py-3.5 border-b border-border">
 <h2 className="font-semibold text-[15px] text-foreground">
 {modal.mode ==='create'?'Auftragsart anlegen':'Auftragsart bearbeiten'}
 </h2>
 <button onClick={() => setModal(null)} className="w-7 h-7 flex items-center justify-center rounded hover:bg-muted text-muted-foreground">
 <X size={16} />
 </button>
 </div>

 <div className="px-5 py-4 space-y-3">
 <div className="grid grid-cols-3 gap-3">
 <div>
 <label className={labelCls}>Code *</label>
 <input value={modal.data.code} onChange={(e) => updateField('code', e.target.value.toUpperCase())} placeholder="AB"className={inputCls} />
 </div>
 <div className="col-span-2">
 <label className={labelCls}>Bezeichnung *</label>
 <input value={modal.data.label} onChange={(e) => updateField('label', e.target.value)} className={inputCls} />
 </div>
 </div>
 <div className="grid grid-cols-2 gap-3">
 <div>
 <label className={labelCls}>Farbe *</label>
 <div className="flex items-center gap-2">
 <input
 type="color"
 value={modal.data.color}
 onChange={(e) => updateField('color', e.target.value)}
 className="h-8 w-10 rounded border border-muted cursor-pointer p-0.5 bg-card"
 />
 <input value={modal.data.color} onChange={(e) => updateField('color', e.target.value)} className={`${inputCls} font-mono`} />
 </div>
 </div>
 <div>
 <label className={labelCls}>Reihenfolge</label>
 <input
 type="number"
 value={modal.data.sort_order}
 onChange={(e) => updateField('sort_order', Number(e.target.value))}
 className={inputCls}
 />
 </div>
 </div>

 {error && (
 <p className="text-[12px] text-destructive bg-status-red-soft border border-status-red-strong rounded px-2.5 py-1.5">
 {error}
 </p>
 )}
 </div>

 <div className="flex items-center justify-end gap-2 px-5 py-3 border-t border-border">
 <button onClick={() => setModal(null)} className="h-8 px-4 text-[13px] font-medium rounded border border-muted text-foreground hover:bg-muted transition-colors">
 Abbrechen
 </button>
 <button
 onClick={handleSave}
 disabled={saving || !modal.data.code || !modal.data.label}
 className="h-8 px-4 text-[13px] font-medium rounded bg-primary text-white hover:bg-primary-dark disabled:opacity-50 transition-colors"
 >
 {saving ?'Speichern…':'Speichern'}
 </button>
 </div>
 </div>
 </div>
 )}
 </div>
 )
}
