<script setup lang="ts">
import { Link } from '@inertiajs/vue3';
import { computed } from 'vue';
import DataTableActions from './data-table-actions.vue';
import DataTableToolbar from '@/components/data-table/DataTableToolbar.vue';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyTitle,
} from '@/components/ui/empty';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import type { CuttingListItem } from '@/types/cutting';
import type {
    DataTablePagination,
    DataTablePaginationLink,
} from '@/types/data-table';

const props = defineProps<{
    cuttings: CuttingListItem[];
    firstItem?: number;
    pagination?: DataTablePagination;
    paginationLinks?: DataTablePaginationLink[];
}>();

const search = defineModel<string>('search', { default: '' });

const emit = defineEmits<{
    'filters-reset': [];
}>();

const showingCount = computed(() => props.cuttings.length);

const paginationSummary = computed(() => {
    if (!props.pagination) {
        return null;
    }

    const { total } = props.pagination;

    if (total === 0) {
        return 'Menampilkan 0 cutting';
    }

    return `Menampilkan ${showingCount.value} cutting dari ${total}`;
});

function rowNumber(index: number): number {
    return (props.firstItem ?? 1) + index;
}

function statusVariant(status: string): 'default' | 'secondary' | 'destructive' | 'outline' {
    if (status === 'verified') {
        return 'default';
    }

    if (status === 'rejected') {
        return 'destructive';
    }

    if (status === 'completed') {
        return 'secondary';
    }

    return 'outline';
}

interface GroupedCuttingMaterials {
    rawMaterialId: number;
    rawMaterialName: string;
    unitLabel?: string;
    items: any[];
}

interface GroupedCuttingResults {
    productId: number;
    productName: string;
    items: any[];
}

function getGroupedMaterials(materials: any[]): GroupedCuttingMaterials[] {
    const groups: Record<number, GroupedCuttingMaterials> = {};

    materials.forEach((item) => {
        const rawMaterial = item.raw_material_price?.raw_material;
        const rawMaterialId = rawMaterial?.id ?? 0;
        const rawMaterialName = rawMaterial?.name ?? 'Bahan Baku Tidak Diketahui';
        const unitLabel = rawMaterial?.unit_label;

        if (!groups[rawMaterialId]) {
            groups[rawMaterialId] = {
                rawMaterialId,
                rawMaterialName,
                unitLabel,
                items: [],
            };
        }

        groups[rawMaterialId].items.push(item);
    });

    return Object.values(groups);
}

function getGroupedResults(results: any[]): GroupedCuttingResults[] {
    const groups: Record<number, GroupedCuttingResults> = {};

    results.forEach((item) => {
        const product = item.product_variant?.product;
        const productId = product?.id ?? 0;
        const productName = product?.name ?? 'Produk Tidak Diketahui';

        if (!groups[productId]) {
            groups[productId] = {
                productId,
                productName,
                items: [],
            };
        }

        groups[productId].items.push(item);
    });

    return Object.values(groups);
}

function getMaterialUnit(materials: any[]): string | undefined {
    return materials[0]?.raw_material_price?.raw_material?.unit_abbreviation;
}

const CM_PER_YARD = 91.44;
const CM_PER_METER = 100;

function formatTotalMaterialUsage(totalUsage: number | null | undefined, materials: any[]): string {
    if (!totalUsage || !materials.length) {
        return '0';
    }

    const unit = materials[0]?.raw_material_price?.raw_material?.unit;

    if (unit === 'yard') {
        return (totalUsage * CM_PER_YARD).toFixed(2);
    }

    if (unit === 'meter') {
        return (totalUsage * CM_PER_METER).toFixed(2);
    }

    return totalUsage.toFixed(2);
}

function getTotalMaterialUsageUnit(materials: any[]): string {
    const unit = materials[0]?.raw_material_price?.raw_material?.unit;

    if (unit === 'yard' || unit === 'meter') {
        return 'cm';
    }

    return materials[0]?.raw_material_price?.raw_material?.unit_abbreviation ?? '';
}

</script>

<template>
    <div class="space-y-4">
        <DataTableToolbar v-model:search="search" @filters-reset="emit('filters-reset')" />

        <div v-if="cuttings.length" class="space-y-4">
            <div v-for="(cutting, index) in cuttings" :key="cutting.id" class="overflow-hidden rounded-md border">
                <div
                    class="flex flex-col gap-3 border-b bg-muted/30 px-4 py-3 sm:flex-row sm:items-start sm:justify-between">
                    <div class="flex min-w-0 items-start gap-3">
                        <span class="text-muted-foreground w-8 shrink-0 pt-0.5 text-center text-sm tabular-nums">
                            {{ rowNumber(index) }}
                        </span>
                        <div class="min-w-0 space-y-2">
                            <div class="flex flex-wrap items-center gap-2">
                                <h3 class="font-medium leading-tight">
                                    Cutting #{{ cutting.id }}
                                </h3>
                                <Badge :variant="statusVariant(cutting.status)">
                                    {{ cutting.status_label }}
                                </Badge>
                            </div>
                            <div class="text-muted-foreground space-y-1 text-sm">
                                <p>{{ cutting.created_at_formatted }}</p>
                                <p>Oleh {{ cutting.created_by?.profile?.full_name ?? cutting.created_by?.username }}</p>
                            </div>
                            <p v-if="cutting.description" class="text-muted-foreground text-sm">
                                {{ cutting.description }}
                            </p>
                            <p v-if="cutting.rejection?.reason" class="text-destructive text-sm">
                                Alasan ditolak: {{ cutting.rejection.reason }}
                            </p>
                            <div class="flex flex-wrap gap-x-4 gap-y-1 text-sm">
                                <span>Total Hasil Cutting <strong class="text-primary">{{ cutting.total_result_pieces ??
                                    0 }} pcs</strong></span>
                                <span>Total Pemakaian Bahan <strong class="text-primary">{{
                                    formatTotalMaterialUsage(cutting.total_material_usage, cutting.materials) }}
                                    {{ getTotalMaterialUsageUnit(cutting.materials) }}</strong></span>
                                <span>Biaya Bahan <strong class="text-primary">{{
                                    cutting.total_material_cost_formatted ?? 'Rp 0' }}</strong></span>
                            </div>
                        </div>
                    </div>

                    <div class="flex shrink-0 items-center justify-end gap-2 sm:pt-0.5">
                        <DataTableActions :cutting="cutting" />
                    </div>  
                </div>

                <div class="space-y-6 p-4">
                    <div class="space-y-2">
                        <h4 class="text-sm font-semibold tracking-tight text-foreground">Bahan Baku</h4>
                        <div class="rounded-md border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Varian</TableHead>
                                        <TableHead>Pemakaian</TableHead>
                                        <TableHead>Sisa</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    <TableRow v-if="!cutting.materials.length" :key="`${cutting.id}-material-empty`">
                                        <TableCell colspan="3" class="text-muted-foreground">
                                            Belum ada bahan baku
                                        </TableCell>
                                    </TableRow>
                                    <template v-else v-for="group in getGroupedMaterials(cutting.materials)"
                                        :key="group.rawMaterialId">
                                        <TableRow class="bg-muted/20 hover:bg-muted/20">
                                            <TableCell colspan="3" class="font-semibold text-foreground">
                                                {{ group.rawMaterialName }}
                                                <Badge v-if="group.unitLabel" variant="secondary"
                                                    class="ml-2 font-normal">
                                                    {{ group.unitLabel }}
                                                </Badge>
                                            </TableCell>
                                        </TableRow>
                                        <TableRow v-for="material in group.items" :key="material.id">
                                            <TableCell class="pl-6 font-medium">
                                                {{ material.raw_material_price?.variant }}
                                            </TableCell>
                                            <TableCell class="tabular-nums">
                                                {{ material.material_usage_formatted }}
                                                <span v-if="material.uses_length_unit" class="text-muted-foreground">
                                                    ({{ material.material_usage_cm_formatted }})
                                                </span>
                                            </TableCell>
                                            <TableCell class="tabular-nums">
                                                {{ material.remaining_material_formatted }}
                                                <span v-if="material.uses_length_unit" class="text-muted-foreground">
                                                    ({{ material.remaining_material_cm_formatted }})
                                                </span>
                                            </TableCell>
                                        </TableRow>
                                    </template>
                                </TableBody>
                            </Table>
                        </div>
                    </div>

                    <div class="space-y-2">
                        <h4 class="text-sm font-semibold tracking-tight text-foreground">Hasil Produk</h4>
                        <div class="rounded-md border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Varian</TableHead>
                                        <TableHead>Hasil</TableHead>
                                        <TableHead>Bagus</TableHead>
                                        <TableHead>Reject</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    <TableRow v-if="!cutting.results.length" :key="`${cutting.id}-result-empty`">
                                        <TableCell colspan="4" class="text-muted-foreground">
                                            Belum ada hasil produk
                                        </TableCell>
                                    </TableRow>
                                    <template v-else v-for="group in getGroupedResults(cutting.results)"
                                        :key="group.productId">
                                        <TableRow class="bg-muted/20 hover:bg-muted/20">
                                            <TableCell colspan="4" class="font-semibold text-foreground">
                                                {{ group.productName }}
                                            </TableCell>
                                        </TableRow>
                                        <TableRow v-for="result in group.items" :key="result.id">
                                            <TableCell class="pl-6 font-medium">
                                                {{ result.product_variant?.name }}
                                            </TableCell>
                                            <TableCell class="tabular-nums">
                                                {{ result.cutting_result }} pcs
                                            </TableCell>
                                            <TableCell class="tabular-nums">
                                                {{ result.warehouse_stock }} pcs
                                            </TableCell>
                                            <TableCell class="tabular-nums">
                                                {{ result.cutting_reject }} pcs
                                            </TableCell>
                                        </TableRow>
                                    </template>
                                </TableBody>
                            </Table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div v-else class="rounded-md border px-6 py-10">
            <Empty>
                <EmptyHeader>
                    <EmptyTitle>Data tidak ditemukan</EmptyTitle>
                    <EmptyDescription>
                        Silakan lakukan pencarian untuk menemukan data yang Anda cari.
                    </EmptyDescription>
                </EmptyHeader>
            </Empty>
        </div>

        <div v-if="pagination" class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <p class="text-muted-foreground text-sm">
                {{ paginationSummary }}
            </p>

            <div v-if="paginationLinks?.length && pagination.lastPage > 1"
                class="flex flex-wrap items-center justify-center gap-1 sm:justify-end">
                <Button v-for="link in paginationLinks" :key="`${link.label}-${link.url}`" variant="outline" size="sm"
                    :disabled="!link.url || link.active" as-child>
                    <Link v-if="link.url" :href="link.url" preserve-scroll>
                        <span v-html="link.label" />
                    </Link>
                    <span v-else v-html="link.label" />
                </Button>
            </div>
        </div>
    </div>
</template>
