<script setup lang="ts">
import { ref } from 'vue'
import { Head, router, usePage } from '@inertiajs/vue3'
import AppLayout from "@/layouts/AppLayout.vue"
import { BreadcrumbItem } from "@/types"

import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import {
    Table, TableHeader, TableRow, TableHead, TableBody, TableCell
} from "@/components/ui/table"
import {
    Tabs,
    TabsContent,
    TabsList,
    TabsTrigger,
} from '@/components/ui/tabs'
import { Select, SelectTrigger, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectValue, } from "@/components/ui/select"

import { toast } from 'vue-sonner'

const page = usePage()

// ======================
//   STATE
// ======================
const consumables = ref<any[]>(page.props.consumables ?? [])
const installers = ref<any[]>(page.props.installers ?? [])
const logs = ref<any[]>(page.props.logs ?? [])
const installerStocks = ref<any[]>(page.props.installerStocks ?? [])

const userRole = page.props.auth?.user?.role
const canSeeConsumables = ['admin', 'engineer'].includes(userRole)

const newConsumable = ref({ name: '', unit: '', stock: 0 })

// ======================
//   DELETE MODAL
// ======================
const showDeleteModal = ref(false)
const consumableToDelete = ref<any | null>(null)

const confirmDelete = (c: any) => {
    consumableToDelete.value = c
    showDeleteModal.value = true
}

const performDelete = () => {
    if (!consumableToDelete.value) return
    const c = consumableToDelete.value

    router.delete(`/consumables/${c.id}`, {
        onSuccess: () => {
            consumables.value = consumables.value.filter(i => i.id !== c.id)
            installerStocks.value.forEach(inst =>
                inst.stocks = inst.stocks.filter((s: any) => s.id !== c.id)
            )
            toast.success('Удалено')
        },
        onError: () => toast.error('Ошибка'),
    })

    showDeleteModal.value = false
    consumableToDelete.value = null
}

// ======================
//   CRUD
// ======================
const addConsumable = () => {
    if (!newConsumable.value.name) return

    const tempId = Date.now()

    consumables.value.push({ ...newConsumable.value, id: tempId })

    installerStocks.value.forEach(inst => {
        inst.stocks.push({
            id: tempId,
            name: newConsumable.value.name,
            unit: newConsumable.value.unit,
            central_stock: newConsumable.value.stock,
            personal_stock: 0
        })
    })

    router.post('/consumables', newConsumable.value, {
        onSuccess: (page) => {
            const last = page.props.consumables.slice(-1)[0]
            const index = consumables.value.findIndex(c => c.id === tempId)
            if (index !== -1) consumables.value[index].id = last.id

            installerStocks.value.forEach(inst => {
                const stock = inst.stocks.find((s: any) => s.id === tempId)
                if (stock) stock.id = last.id
            })
        },
        onError: () => {
            consumables.value = consumables.value.filter(c => c.id !== tempId)
            installerStocks.value.forEach(inst => {
                inst.stocks = inst.stocks.filter((s: any) => s.id !== tempId)
            })
            toast.error('Ошибка при добавлении')
        },
    })

    newConsumable.value = { name: '', unit: '', stock: 0 }
    toast.success('Расходник добавлен')
}

const updateConsumable = (c: any) => {
    router.put(`/consumables/${c.id}`, c, {
        preserveScroll: true,
        onSuccess: () => toast.success('Сохранено'),
        onError: () => toast.error('Ошибка'),
    })
}

// ======================
//   CENTRAL STOCK +/-
// ======================
const adjust = (c: any, delta: number) => {
    if (c.stock + delta < 0) return
    c.stock += delta

    installerStocks.value.forEach(installer => {
        const s = installer.stocks.find((s: any) => s.id === c.id)
        if (s) s.central_stock += delta
    })

    router.post(`/consumables/${c.id}/adjust`, { delta }, {
        preserveScroll: true,
        onSuccess: () => {
            toast.success(delta > 0 ? 'Остаток увеличен' : 'Остаток уменьшен')
        },
        onError: () => {
            c.stock -= delta
            installerStocks.value.forEach(installer => {
                const s = installer.stocks.find((s: any) => s.id === c.id)
                if (s) s.central_stock -= delta
            })
            toast.error('Ошибка изменения остатка')
        }
    })
}

// ======================
//   REFILL MODAL
// ======================
const showModal = ref(false)
const selectedConsumable = ref<number | null>(null)
const selectedInstaller = ref<number | null>(null)
const quantity = ref(1)

const openModal = (cId: number) => {
    selectedConsumable.value = cId
    selectedInstaller.value = null
    quantity.value = 1
    showModal.value = true
}

const refill = () => {
    if (!selectedConsumable.value || !selectedInstaller.value) return
    const c = consumables.value.find(c => c.id === selectedConsumable.value)
    if (!c || c.stock < quantity.value) {
        toast.error('Недостаточно на складе')
        return
    }

    const installerStock = installerStocks.value.find(
        i => i.installer_id === Number(selectedInstaller.value)
    )
    const installerData = installers.value.find(
        i => i.id === Number(selectedInstaller.value)
    )

    // optimistic update
    c.stock -= quantity.value
    if (installerStock) {
        const s = installerStock.stocks.find((s: any) => s.id === c.id)
        if (s) {
            s.central_stock -= quantity.value
            s.personal_stock += quantity.value
        }
    }

    router.post(`/consumables/${selectedInstaller.value}/refill`, {
        consumable_id: selectedConsumable.value,
        quantity: quantity.value
    }, {
        preserveScroll: true,
        onSuccess: () => {
            toast.success('Выдано')
            showModal.value = false

            logs.value.unshift({
                id: Date.now(),
                created_at: new Date().toISOString(),
                type: 'issue',
                quantity: quantity.value,
                consumable: c ? { ...c } : null,
                installer: installerData ? { id: installerData.id, name: installerData.name } : null,
            })
        },
        onError: () => {
            c.stock += quantity.value
            if (installerStock) {
                const s = installerStock.stocks.find((s: any) => s.id === c.id)
                if (s) {
                    s.central_stock += quantity.value
                    s.personal_stock -= quantity.value
                }
            }
            toast.error('Ошибка выдачи')
        }
    })
}

// ======================
//   UI
// ======================
const typeLabels: Record<string, string> = {
    issue: "Выдан",
    return: "Возврат",
    adjust: "Корректировка",
    create: "Создание",
    delete: "Удаление",
    personal_issue: "Списано с личного склада",
}

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Склад', href: '/consumables' },
]
</script>

<template>
    <Head title="Склад" />

    <AppLayout :breadcrumbs="breadcrumbs">
        <div class="p-6">
            <h1 class="text-2xl font-bold mb-4">Склад</h1>

            <Tabs :default-value="canSeeConsumables ? 'installers' : 'installers'" class="space-y-4">

                <!-- Список табов -->
                <TabsList>
                    <TabsTrigger value="installers" class="cursor-pointer">Личный склад монтажников</TabsTrigger>
                    <TabsTrigger value="consumables" class="cursor-pointer" v-if="canSeeConsumables">Расходники на ЦС</TabsTrigger>
                    <TabsTrigger value="logs" class="cursor-pointer">История</TabsTrigger>
                </TabsList>

                <!-- Таб: Монтажники -->
                <TabsContent value="installers">
                    <Table class="mb-4">
                        <TableHeader>
                            <TableRow>
                                <TableHead>Монтажник</TableHead>
                                <TableHead>Расходник</TableHead>
                                <TableHead>Центральный склад</TableHead>
                                <TableHead>Личный склад</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            <TableRow v-for="installer in installerStocks" :key="installer.installer_id">
                                <TableCell>{{ installer.installer_name }}</TableCell>
                                <TableCell>
                                    <div v-for="s in installer.stocks" :key="s.id">{{ s.name }}</div>
                                </TableCell>
                                <TableCell>
                                    <div v-for="s in installer.stocks" :key="s.id">{{ s.central_stock }}</div>
                                </TableCell>
                                <TableCell>
                                    <div v-for="s in installer.stocks" :key="s.id">{{ s.personal_stock }}</div>
                                </TableCell>
                            </TableRow>
                        </TableBody>
                    </Table>
                </TabsContent>

                <!-- Таб: Расходники -->
                <TabsContent value="consumables" v-if="canSeeConsumables">
                    <!-- Добавление расходника -->
                    <div class="mb-4 flex gap-2">
                        <Input v-model="newConsumable.name" placeholder="Название" />
                        <Input v-model="newConsumable.unit" placeholder="Ед. изм." />
                        <Input v-model.number="newConsumable.stock" type="number" placeholder="Остаток" class="w-24" />
                        <Button @click="addConsumable">Добавить</Button>
                    </div>

                    <!-- Таблица расходников -->
                    <Table>
                        <TableHeader>
                            <TableRow>
                                <TableHead>ID</TableHead>
                                <TableHead>Название</TableHead>
                                <TableHead>Ед.</TableHead>
                                <TableHead>Остаток</TableHead>
                                <TableHead>Действия</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            <TableRow v-for="c in consumables" :key="c.id">
                                <TableCell>{{ c.id }}</TableCell>
                                <TableCell><Input v-model="c.name" /></TableCell>
                                <TableCell><Input v-model="c.unit" /></TableCell>
                                <TableCell>
                                    <div class="flex items-center gap-2">
                                        <Button variant="destructive" size="sm" @click="adjust(c, -1)">-</Button>
                                        <Input v-model.number="c.stock" type="number" class="w-20 text-center" />
                                        <Button variant="success" size="sm" @click="adjust(c, 1)">+</Button>
                                    </div>
                                </TableCell>
                                <TableCell class="flex gap-2">
                                    <Button variant="outline" size="sm" @click="updateConsumable(c)">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-save-icon lucide-save"><path d="M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"/><path d="M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"/><path d="M7 3v4a1 1 0 0 0 1 1h7"/></svg>
                                    </Button>
                                    <Button variant="secondary" size="sm" @click="openModal(c.id)">
                                        ➜ Выдать монтажнику
                                    </Button>
                                    <Button variant="destructive" size="sm" @click="confirmDelete(c)">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-icon lucide-trash"><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/><path d="M3 6h18"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>
                                    </Button>
                                </TableCell>
                            </TableRow>
                        </TableBody>
                    </Table>
                </TabsContent>

                <!-- Таб: История -->
                <TabsContent value="logs">
                    <div v-if="logs.length === 0" class="text-gray-500">Истории пока нет</div>
                    <Table v-else>
                        <TableHeader>
                            <TableRow>
                                <TableHead>Дата</TableHead>
                                <TableHead>Расходник</TableHead>
                                <TableHead>Операция</TableHead>
                                <TableHead>Кол-во</TableHead>
                                <TableHead>Монтажник</TableHead>
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            <TableRow v-for="l in logs" :key="l.id">
                                <TableCell>{{ new Date(l.created_at).toLocaleString() }}</TableCell>
                                <TableCell>{{ l.consumable?.name ?? 'Удалён' }}</TableCell>
                                <TableCell :class="{
                  'text-blue-600': l.type==='issue',
                  'text-orange-600': l.type==='adjust',
                  'text-green-600': l.type==='return',
                  'text-red-600': l.type==='delete',
                  'text-gray-600': l.type==='create'
                }">{{ typeLabels[l.type] || l.type || '—' }}</TableCell>
                                <TableCell>{{ l.quantity }}</TableCell>
                                <TableCell>{{ l.installer?.name ?? '-' }}</TableCell>
                            </TableRow>
                        </TableBody>
                    </Table>
                </TabsContent>

            </Tabs>

            <!-- Модалка выдачи расходника -->
            <div v-if="showModal" class="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
                <div class="bg-white p-6 rounded-xl shadow-xl w-[400px]">
                    <h2 class="text-xl font-bold mb-4">Выдать расходник</h2>
                    <label>Монтажник</label>
                    <Select v-model="selectedInstaller">
                        <SelectTrigger class="w-full mb-3">
                            <SelectValue placeholder="Выберите монтажника" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectGroup>
                                <SelectLabel>Монтажники</SelectLabel>
                                <SelectItem v-for="i in installers" :key="i.id" :value="String(i.id)">{{ i.name }}</SelectItem>
                            </SelectGroup>
                        </SelectContent>
                    </Select>
                    <label>Количество</label>
                    <Input type="number" v-model="quantity" min="1" class="mb-4" />
                    <div class="flex justify-end gap-2">
                        <Button variant="outline" @click="showModal = false">Отмена</Button>
                        <Button @click="refill">Выдать</Button>
                    </div>
                </div>
            </div>

            <!-- Модалка удаления расходника -->
            <div v-if="showDeleteModal" class="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
                <div class="bg-white p-6 rounded-xl shadow-xl w-[400px]">
                    <h2 class="text-xl font-bold mb-4">Подтвердите удаление</h2>
                    <p>Вы действительно хотите удалить расходник <strong>{{ consumableToDelete?.name }}</strong>?</p>
                    <div class="flex justify-end gap-2 mt-4">
                        <Button variant="outline" @click="showDeleteModal = false">Отмена</Button>
                        <Button variant="destructive" @click="performDelete">Удалить</Button>
                    </div>
                </div>
            </div>


        </div>
    </AppLayout>
</template>


<style scoped>

</style>
