<script setup lang="ts">
import Heading from '@/components/Heading.vue';
import { onMounted, ref } from "vue"
import AppLayout from '@/layouts/AppLayout.vue';
import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from '@/components/ui/card'
import { invoices } from '@/routes';
import { toRoundedCurrency, toLocalDate } from '@/lib/utils'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from '@/components/ui/tooltip'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { usePage, router } from '@inertiajs/vue3';
import axios, { AxiosError } from "axios";
import { toast } from "vue-sonner";
import { SalesStatistics, Todo, Invoice } from "@/types";
import Todos from '@/components/Todos.vue';
import InvoiceService from '@/services/InvoiceService';
import { Table, TableRow, TableCell } from '@/components/ui/crm-table';

interface Props {
    dueInvoices: Invoice[];
}
const props = defineProps<Props>();
const salesStatistics = ref<SalesStatistics>({
    year: new Date().getFullYear(),
    totalRevenue: 0,
    paid: 0,
    paidPercent: 0,
    draft: 0,
    draftPercent: 0,
    issued: 0,
    issuedPercent: 0,
    due: 0,
    duePercent: 0,
    reminded: 0,
    remindedPercent: 0
})
const salesTarget = ref(60000) // TODO: aus settings
const todos = ref<Todo[]>([])
const showCompleted = ref(false)
const page = usePage();
const token = page.props.flash?.token
if (token) {
    localStorage.setItem('sanctum_token', token)
}


onMounted(async () => {
    // Load Todos
    try {
        let response = await axios.get('/api/todos')
        todos.value = response.data
    } catch (error) {
        toast.error('Fehler beim Laden der Daten', { description: (error as AxiosError).message })
    }

    // Load sales statistics
    try {
        salesStatistics.value = await InvoiceService.getSalesStatistics()
    } catch (error) {
        toast.error('Fehler beim Laden der Daten', { description: (error as AxiosError).message })
    }
})

</script>

<template>

    <AppLayout title="Dashboard">
        <Heading title="Tooloop Multimedia" description="Kundenpflege und Rechnungswesen" />

        <div class="columns-1 lg:columns-2 xl:columns-3 gap-8">



            <!-- Nachrichten -->
            <!-- <Card class="break-inside-avoid mb-12">
                <CardHeader>
                    <CardTitle>Benachrichtigungen</CardTitle>
                    <CardDescription>Card Description</CardDescription>
                </CardHeader>
                <CardContent class="flex flex-col gap-4">

                    <Alert class="bg-muted pr-8">
                        <Trophy class="h-4 w-4 stroke-amber-600" />
                        <AlertTitle>Du hast zwei neue Erfolge</AlertTitle>
                        <AlertDescription class="text-sky-600">
                            Weiter so
                        </AlertDescription>

                        <Button variant="ghost" class="rounded-full w-6 h-6 absolute top-0.5 right-0.5">
                            <X />
                        </Button>
                    </Alert>

                    <Alert class="bg-muted pr-8">
                        <UserCheck2 class="h-4 w-4 stroke-lime-600" />
                        <AlertTitle>Du hast länger keine Bestandskunden mehr kontaktiert</AlertTitle>
                        <AlertDescription class="text-sky-600">
                            <a href="">Hier sind ein paar Vorschläge für Dich
                                <ChevronRight class="inline h-4 w-4" />
                            </a>
                        </AlertDescription>

                        <Button variant="ghost" class="rounded-full w-6 h-6 absolute top-0.5 right-0.5">
                            <X />
                        </Button>
                    </Alert>

                </CardContent>
                <CardFooter>
                    <Button>Alles leeren</Button>
                </CardFooter>
            </Card> -->


            <!-- Aufgaben -->
            <Card class="break-inside-avoid mb-8 ">
                <CardHeader class="flex justify-between flex-wrap">
                    <div>
                        <CardTitle class="mb-1.5">Aufgaben</CardTitle>
                        <CardDescription class="mb-3">Card Description</CardDescription>
                    </div>

                    <div class="flex items-center gap-2">
                        <Switch id="show-completed" v-model="showCompleted" />
                        <Label for="show-completed" class="text-muted-foreground">Erledigte</Label>
                    </div>
                </CardHeader>
                <CardContent class="max-h-[600px] overflow-y-auto">
                    <Todos :modelValue="todos" :show-completed="showCompleted" :show-todoable="true" />
                </CardContent>
            </Card>

            <!-- Rechnungen -->
            <Card class="break-inside-avoid mb-12">
                <CardHeader>
                    <CardTitle>Fällige Rechnungen</CardTitle>
                    <CardDescription>Card Description</CardDescription>
                </CardHeader>
                <CardContent>
                    <Table class="text-sm">
                        <TableRow v-for="invoice in props.dueInvoices" @mouseover="router.prefetch(invoices())" @click="router.visit(invoices())">
                            <TableCell class="align-top">
                                <span class="whitespace-nowrap" v-if="invoice.dueDate">{{ toLocalDate(invoice.dueDate)
                                    }}</span>
                            </TableCell>
                            <TableCell>
                                <span class="font-semibold">{{ invoice.nr }}</span> {{ invoice.title }}<br>
                                <span class="text-muted-foreground">{{ invoice.billingData?.companyName }}</span>
                            </TableCell>
                            <TableCell class="align-top text-right">{{ toRoundedCurrency(invoice.totalAmount) }}
                            </TableCell>
                        </TableRow>
                    </Table>
                </CardContent>
            </Card>


            <!-- Umsatz -->
            <Card class="break-inside-avoid mb-8 relative overflow-clip">
                <div class="bg-image absolute -inset-6 opacity-30 blur-[2px]"
                    style="background-image: url('/storage/images/patterns/19742.jpg'); background-size: 150%;" </div>
                    <CardHeader class="z-1">
                        <CardTitle>Umsatz {{ salesStatistics?.year || '' }}</CardTitle>
                        <CardDescription>Card Description</CardDescription>
                    </CardHeader>
                    <CardContent class="relative flex flex-col gap-3">

                        <div class="flex items-baseline justify-between">
                            <span class="text-xl font-bold text-primary">{{
                                toRoundedCurrency(salesStatistics?.paid) || '' }}</span>
                            <span>{{ toRoundedCurrency(salesTarget) }}</span>
                        </div>

                        <div class="w-full h-8 bg-secondary dark:bg-neutral-900 rounded-md overflow-clip relative flex">
                            <TooltipProvider :delay-duration="0" v-if="salesStatistics">
                                <!-- Paid -->
                                <Tooltip>
                                    <TooltipTrigger as-child>
                                        <div :style="'width: ' + (salesStatistics.paid / salesTarget * 100) + '%'"
                                            class="bg-primary transition-width duration-500 ease-out"></div>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <strong>Bezahlt</strong>
                                        <p>{{ toRoundedCurrency(salesStatistics.paid) }}</p>
                                    </TooltipContent>
                                </Tooltip>

                                <!-- Issued -->
                                <Tooltip>
                                    <TooltipTrigger as-child>
                                        <div :style="'width: ' + (salesStatistics.issued / salesTarget * 100) + '%'"
                                            class="bg-gray-500 transition-width duration-500 ease-out">
                                        </div>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <strong>Gestellt</strong>
                                        <p>{{ toRoundedCurrency(salesStatistics.issued) }}</p>
                                    </TooltipContent>
                                </Tooltip>

                                <!-- Due -->
                                <Tooltip>
                                    <TooltipTrigger as-child>
                                        <div :style="'width: ' + (salesStatistics.due / salesTarget * 100) + '%'"
                                            class="bg-gray-400 transition-width duration-500 ease-out">
                                        </div>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <strong>Fällig</strong>
                                        <p>{{ toRoundedCurrency(salesStatistics.due) }}</p>
                                    </TooltipContent>
                                </Tooltip>

                                <!-- Reminded -->
                                <Tooltip>
                                    <TooltipTrigger as-child>
                                        <div :style="'width: ' + (salesStatistics.reminded / salesTarget * 100) + '%'"
                                            class="bg-gray-300 transition-width duration-500 ease-out">
                                        </div>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                        <strong>Gemahnt</strong>
                                        <p>{{ toRoundedCurrency(salesStatistics.reminded) }}</p>
                                    </TooltipContent>
                                </Tooltip>

                                <div :style="'width: ' + (salesStatistics.draft / salesTarget * 100) + '%'"
                                    class="bg-muted-500 transition-width duration-500 ease-out">
                                </div>
                            </TooltipProvider>
                        </div>

                    </CardContent>
            </Card>

        </div>


    </AppLayout>
</template>
