import { RowActions } from '@/components/data-display';
import { ImagePreviewButton } from '@/components/dialogs';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from '@/components/ui/popover';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useCan } from '@/hooks/use-can';
import { formatNumber } from '@/lib/format';
import { share as cuttingShare } from '@/routes/admin/manage/cuttings';
import { ChevronDown, Pencil, ScissorsIcon, Share2, Trash2 } from 'lucide-react';
import { useState } from 'react';
import type { Cutting } from './columns';

function generateShareLink(cuttingId: number): string {
    return window.location.origin + cuttingShare.url(cuttingId);
}

function generateWhatsappText(cutting: Cutting): string {
    const result = cutting.cutting_results?.[0];
    const items = cutting.cutting_materials ?? [];
    const shareLink = generateShareLink(cutting.id);

    let text = `*Cutting #${cutting.id}*\n`;
    text += `Status: ${cutting.status === 'completed' ? 'Selesai' : cutting.status === 'cancelled' ? 'Dibatalkan' : 'Dikerjakan'}\n`;
    text += `Tanggal: ${cutting.formatted_created_at}\n`;
    text += `Oleh: ${cutting.created_by?.user_profile?.full_name ?? '-'}\n`;

    if (cutting.description) {
        text += `Deskripsi: ${cutting.description}\n`;
    }

    const productNames = new Set<string>();
    (cutting.cutting_results ?? []).forEach((r) => {
        if (r.product_name) {
            productNames.add(r.product_name);
        }
    });

    if (productNames.size > 0) {
        text += `\nNama Produk: ${Array.from(productNames).join(', ')}\n`;
    }

    const totalUsage = items.reduce(
        (sum, item) => sum + Number(item.material_usage),
        0,
    );
    text += `Total Pemakaian: ${formatNumber(totalUsage)}\n`;

    if (result?.cutting_result) {
        text += `Total Hasil Cutting: ${formatNumber(result.cutting_result)} pcs\n`;
    }

    text += `\nLihat detail lengkap:\n${shareLink}`;

    return text;
}

function openWAWeb(text: string) {
    const encoded = encodeURIComponent(text);
    window.open(`https://wa.me/?text=${encoded}`, '_blank');
}

function openWAAndroid(text: string, pkg: string) {
    const encoded = encodeURIComponent(text);
    window.open(`intent://send?text=${encoded}#Intent;scheme=whatsapp;package=${pkg};end`, '_blank');
}

function shareViaWhatsAppMessenger(text: string) {
    if (/android/i.test(navigator.userAgent)) {
        openWAAndroid(text, 'com.whatsapp');
    } else {
        openWAWeb(text);
    }
}

function shareViaWhatsAppBusiness(text: string) {
    if (/android/i.test(navigator.userAgent)) {
        openWAAndroid(text, 'com.whatsapp.w4b');
    } else {
        openWAWeb(text);
    }
}

export type CuttingCardRowParams = {
    cutting: Cutting;
    index: number;
    isExpanded: boolean;
    onToggleExpand: () => void;
    onComplete: (cutting: Cutting) => void;
    onEdit: (cutting: Cutting) => void;
    onDelete: (cutting: Cutting) => void;
};

export function CuttingCardRow({
    cutting,
    index,
    isExpanded,
    onToggleExpand,
    onComplete,
    onEdit,
    onDelete,
}: CuttingCardRowParams) {
    const { can } = useCan();
    const [shareOpen, setShareOpen] = useState(false);
    const materialsCount = cutting.materials_count ?? 0;
    const totalUsage = cutting.total_usage ?? 0;
    const productName = cutting.product_name ?? '-';
    const cuttingResult = cutting.cutting_result ?? null;

    const shareText = generateWhatsappText(cutting);

    function handleShareWAMessenger() {
        shareViaWhatsAppMessenger(shareText);
        setShareOpen(false);
    }

    function handleShareWABusiness() {
        shareViaWhatsAppBusiness(shareText);
        setShareOpen(false);
    }

    return (
        <>
            <Card className="overflow-hidden">
                <CardContent className="p-0">
                    <div className="flex items-start gap-3 p-4">
                        <Button
                            variant="ghost"
                            size="icon"
                            className="mt-0.5 h-6 w-6 shrink-0"
                            onClick={onToggleExpand}
                        >
                            <ChevronDown
                                className={`h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                            />
                        </Button>

                        <div className="min-w-0 flex-1">
                            <div className="flex flex-wrap items-center gap-2">
                                <span className="text-xs text-muted-foreground">
                                    {index}.
                                </span>
                                <h3>
                                    {productName}
                                </h3>
                            </div>

                            <div className="mt-1 text-xs text-muted-foreground">
                                {materialsCount > 0 && (
                                    <span>
                                        {materialsCount} bahan baku
                                    </span>
                                )}
                                {cutting.description && (
                                    <span className="ml-2">
                                        · {cutting.description}
                                    </span>
                                )}
                            </div>

                            <div className="mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
                                <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
                                    {cutting.formatted_created_at}
                                </span>
                                <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 font-medium text-foreground">
                                    {cutting.status === 'completed'
                                        ? 'Selesai'
                                        : cutting.status === 'cancelled'
                                            ? 'Dibatalkan'
                                            : 'Dikerjakan'}
                                </span>
                            </div>

                            <div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
                                <span>
                                    <span className="text-muted-foreground">
                                        Pemakaian:{' '}
                                    </span>
                                    {formatNumber(totalUsage)}
                                </span>
                                {cuttingResult && (
                                    <span>
                                        <span className="text-muted-foreground">
                                            Hasil:{' '}
                                        </span>
                                        {formatNumber(cuttingResult)}
                                    </span>
                                )}
                                {cutting.formatted_cost_per_unit && (
                                    <span className="font-semibold">
                                        <span className="font-normal text-muted-foreground">
                                            Per Produk:{' '}
                                        </span>
                                        {cutting.formatted_cost_per_unit}
                                    </span>
                                )}
                                {cutting.formatted_total_material_cost && (
                                    <span className="font-semibold">
                                        <span className="font-normal text-muted-foreground">
                                            Biaya Keseluruhan:{' '}
                                        </span>
                                        {cutting.formatted_total_material_cost}
                                    </span>
                                )}
                            </div>

                            {cutting.photo_urls && cutting.photo_urls.length > 0 && (
                                <div className="mt-2">
                                    <ImagePreviewButton
                                        srcs={cutting.photo_conversion_urls?.length ? cutting.photo_conversion_urls : cutting.photo_urls}
                                        modalSrcs={cutting.photo_urls}
                                        title={productName}
                                        description={cutting.description ?? cutting.formatted_created_at}
                                        className="h-16 w-16"
                                    />
                                </div>
                            )}
                        </div>

                        <div className="flex shrink-0 items-center gap-1">
                            <Tooltip>
                                <Popover open={shareOpen} onOpenChange={setShareOpen}>
                                    <TooltipTrigger asChild>
                                        <PopoverTrigger asChild>
                                            <Button variant="ghost" size="icon" className="h-8 w-8">
                                                <Share2 className="h-4 w-4" />
                                            </Button>
                                        </PopoverTrigger>
                                    </TooltipTrigger>
                                    <TooltipContent>Bagikan</TooltipContent>
                                    <PopoverContent align="end" className="w-48 space-y-1 p-2">
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="w-full justify-start gap-2"
                                            onClick={handleShareWAMessenger}
                                        >
                                            WhatsApp Messenger
                                        </Button>
                                        <Button
                                            variant="ghost"
                                            size="sm"
                                            className="w-full justify-start gap-2"
                                            onClick={handleShareWABusiness}
                                        >
                                            WhatsApp Business
                                        </Button>
                                    </PopoverContent>
                                </Popover>
                            </Tooltip>
                            {(can('cuttings.update') || can('cuttings.delete')) && (
                                <RowActions
                                    actions={[
                                        {
                                            label: 'Selesaikan',
                                            icon: <ScissorsIcon className="h-4 w-4" />,
                                            show: can('cuttings.complete') && cutting.status === 'in_progress',
                                            onClick: () => onComplete(cutting),
                                        },
                                        {
                                            label: 'Edit',
                                            icon: <Pencil className="h-4 w-4" />,
                                            show: can('cuttings.update'),
                                            onClick: () => onEdit(cutting),
                                        },
                                        {
                                            label: 'Hapus',
                                            icon: (
                                                <Trash2 className="h-4 w-4 text-destructive" />
                                            ),
                                            show: can('cuttings.delete'),
                                            onClick: () => onDelete(cutting),
                                        },
                                    ]}
                                    wrapperClassName="flex shrink-0 items-center gap-1"
                                />
                            )}
                        </div>
                    </div>
                </CardContent>
            </Card>
        </>
    );
}
