'use client'

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

interface Props {
 initialProjects: PlanningProject[]
 perms: PlanningPerms
}

type ProjectForm = Omit<PlanningProject,'id'|'created_at'>

const EMPTY: ProjectForm = {
 code:'',
 name:'',
 supplier_id: null,
 location_label: null,
 country: null,
 is_active: true,
}

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 PlanningProjectsClient({ initialProjects, perms }: Props) {
 const [projects, setProjects] = useState<PlanningProject[]>(initialProjects)
 const [modal, setModal] = useState<{ mode:'create'|'edit'; data: ProjectForm; id?: string } | null>(null)
 const [saving, setSaving] = useState(false)
 const [error, setError] = useState<string | null>(null)
 const [search, setSearch] = useState('')
 const [showInactive, setShowInactive] = useState(false)

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

 async function refresh() {
 const { data } = await supabase.from('planning_projects').select('*').order('code')
 if (data) setProjects(data as PlanningProject[])
 }

 function openCreate() {
 setModal({ mode:'create', data: { ...EMPTY } })
 setError(null)
 }

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

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

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

 const payload = {
 ...modal.data,
 supplier_id: modal.data.supplier_id || null,
 location_label: modal.data.location_label || null,
 country: modal.data.country || null,
 }

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

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

 async function handleToggleActive(p: PlanningProject) {
 if (!canManage) return
 await supabase.from('planning_projects').update({ is_active: !p.is_active }).eq('id', p.id)
 await refresh()
 }

 const filtered = projects.filter((p) => {
 if (!showInactive && !p.is_active) return false
 if (search) {
 const q = search.toLowerCase()
 return p.code.toLowerCase().includes(q) || p.name.toLowerCase().includes(q)
 }
 return true
 })

 return (
 <div className="flex-1 overflow-y-auto bg-muted">
 {/* Toolbar */}
 <div className="bg-card border-b border-muted px-6 py-3 flex items-center gap-3">
 <input
 type="text"
 placeholder="Suchen (Code, Name)…"
 value={search}
 onChange={(e) => setSearch(e.target.value)}
 className="h-8 rounded border border-muted text-[13px] text-foreground px-2 bg-card focus:outline-none focus:border-primary w-52"
 />
 <label className="flex items-center gap-2 cursor-pointer select-none text-[12px] text-[#555555]">
 <input
 type="checkbox"
 checked={showInactive}
 onChange={(e) => setShowInactive(e.target.checked)}
 className="w-4 h-4 accent-primary"
 />
 Inaktive anzeigen
 </label>
 <span className="text-[12px] text-muted-foreground">{filtered.length} Projekte</span>
 {canManage && (
 <button
 onClick={openCreate}
 className="ml-auto 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={14} />
 Neues Projekt
 </button>
 )}
 </div>

 {/* Table */}
 <div className="px-6 py-4">
 <div className="bg-card rounded-xl border border-muted overflow-hidden">
 <table className="w-full text-[12px] border-collapse">
 <thead>
 <tr className="border-b-2 border-muted bg-muted">
 <th className="text-left px-4 py-2 font-semibold text-foreground">Code</th>
 <th className="text-left px-4 py-2 font-semibold text-foreground">Name</th>
 <th className="text-left px-4 py-2 font-semibold text-foreground">Standort</th>
 <th className="text-left px-4 py-2 font-semibold text-foreground">Land</th>
 <th className="text-center px-4 py-2 font-semibold text-foreground">Status</th>
 {canManage && <th className="px-4 py-2"/>}
 </tr>
 </thead>
 <tbody>
 {filtered.map((p, i) => (
 <tr
 key={p.id}
 className={`border-b border-muted ${i % 2 === 0 ?'bg-card':'bg-background'} ${!p.is_active ?'opacity-50':''}`}
 >
 <td className="px-4 py-2">
 <span className="font-mono font-semibold text-primary">{p.code}</span>
 </td>
 <td className="px-4 py-2 font-medium text-foreground">{p.name}</td>
 <td className="px-4 py-2 text-muted-foreground">{p.location_label ??'—'}</td>
 <td className="px-4 py-2 text-muted-foreground">{p.country ??'—'}</td>
 <td className="px-4 py-2 text-center">
 {canManage ? (
 <button
 onClick={() => handleToggleActive(p)}
 className={`px-2 py-0.5 rounded text-[11px] font-medium cursor-pointer transition-colors ${
 p.is_active ?'bg-[#F0FDF4] text-[#65A30D] hover:bg-[#DCFCE7]':'bg-muted text-muted-foreground hover:bg-[#EEEEEE]'
 }`}
 >
 {p.is_active ?'Aktiv':'Inaktiv'}
 </button>
 ) : (
 <span className={`px-2 py-0.5 rounded text-[11px] font-medium ${p.is_active ?'bg-[#F0FDF4] text-[#65A30D]':'bg-muted text-muted-foreground'}`}>
 {p.is_active ?'Aktiv':'Inaktiv'}
 </span>
 )}
 </td>
 {canManage && (
 <td className="px-4 py-2 text-right">
 <button
 onClick={() => openEdit(p)}
 className="w-7 h-7 flex items-center justify-center rounded hover:bg-muted text-muted-foreground ml-auto"
 >
 <Pencil size={13} />
 </button>
 </td>
 )}
 </tr>
 ))}
 </tbody>
 </table>
 </div>
 </div>

 {/* 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-md 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'?'Projekt anlegen':'Projekt 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="P-001"
 className={inputCls}
 />
 </div>
 <div className="col-span-2">
 <label className={labelCls}>Projektname *</label>
 <input value={modal.data.name} onChange={(e) => updateField('name', e.target.value)} className={inputCls} />
 </div>
 </div>
 <div className="grid grid-cols-2 gap-3">
 <div>
 <label className={labelCls}>Standort</label>
 <input value={modal.data.location_label ??''} onChange={(e) => updateField('location_label', e.target.value || null)} placeholder="z.B. München"className={inputCls} />
 </div>
 <div>
 <label className={labelCls}>Land</label>
 <input value={modal.data.country ??''} onChange={(e) => updateField('country', e.target.value || null)} placeholder="z.B. DE"className={inputCls} />
 </div>
 </div>
 <label className="flex items-center gap-2 cursor-pointer select-none">
 <input
 type="checkbox"
 checked={modal.data.is_active}
 onChange={(e) => updateField('is_active', e.target.checked)}
 className="w-4 h-4 accent-primary"
 />
 <span className="text-[13px] text-foreground">Aktiv</span>
 </label>

 {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.name}
 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>
 )
}
