import { Briefcase, ChevronDown, Copy, MessageCircle, Pencil, Share2, Trash2 } from 'lucide-react';
import { useState } from 'react';
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 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;
    onEdit: (cutting: Cutting) => void;
    onDelete: (cutting: Cutting) => void;
};

export function CuttingCardRow({
    cutting,
    index,
    isExpanded,
    onToggleExpand,
    onEdit,
    onDelete,
}: CuttingCardRowParams) {
    const { can } = useCan();
    const [shareOpen, setShareOpen] = useState(false);
    const [copied, setCopied] = useState(false);
    const items = cutting.cutting_materials ?? [];
    const result = cutting.cutting_results?.[0];
    const singleCount = items.filter(
        (item) => item.combination_id === null,
    ).length;
    const comboCount = new Set(
        items
            .filter((item) => item.combination_id !== null)
            .map((item) => item.combination_id),
    ).size;
    const materialCount = singleCount + comboCount;
    const productName = result?.product_name ?? '-';
    const totalUsage = items.reduce(
        (sum, item) => sum + Number(item.material_usage),
        0,
    );

    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 className="truncate font-medium">
                                    {productName}
                                </h3>
                            </div>

                            <div className="mt-1 text-xs text-muted-foreground">
                                {materialCount > 0 && (
                                    <span>
                                        {materialCount} 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>
                                {result?.cutting_result && (
                                    <span>
                                        <span className="text-muted-foreground">
                                            Hasil:{' '}
                                        </span>
                                        {formatNumber(result.cutting_result)}
                                    </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_url && (
                                <div className="mt-2">
                                    <ImagePreviewButton
                                        srcs={[cutting.photo_conversion_url ?? cutting.photo_url]}
                                        modalSrc={cutting.photo_url}
                                        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: '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>
        </>
    );
}
