import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/Components/ui/dialog";
import { Badge } from "@/Components/ui/badge";
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import { User, Clock, Package, Activity as ActivityIcon } from "lucide-react";

interface Activity {
    id: number;
    description: string;
    subject_type: string;
    event: string;
    causer: string;
    created_at: string;
    properties: {
        attributes?: Record<string, any>;
        old?: Record<string, any>;
        snapshot?: Record<string, any>;
        sub_subject?: string;
        items_diff?: {
            added: any[];
            removed: any[];
            updated: any[];
        };
    };
}

interface Props {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    activity: Activity | null;
}

// 欄位翻譯對照表
const fieldLabels: Record<string, string> = {
    name: '名稱',
    code: '商品代號',
    username: '登入帳號',
    description: '描述',
    price: '價格',
    cost: '成本',
    stock: '庫存',
    category_id: '分類',
    unit_id: '單位',
    is_active: '啟用狀態',
    conversion_rate: '換算率',
    specification: '規格',
    brand: '品牌',
    base_unit_id: '基本單位',
    large_unit_id: '大單位',
    purchase_unit_id: '採購單位',
    email: 'Email',
    password: '密碼',
    phone: '電話',
    address: '地址',
    role_id: '角色',
    email_verified_at: '電子郵件驗證時間',
    remember_token: '登入權杖',
    // 快照欄位
    category_name: '分類名稱',
    base_unit_name: '基本單位名稱',
    large_unit_name: '大單位名稱',
    purchase_unit_name: '採購單位名稱',
    // 廠商欄位
    short_name: '簡稱',
    tax_id: '統編',
    owner: '負責人',
    contact_name: '聯絡人',
    tel: '電話',
    remark: '備註',
    // 倉庫與庫存欄位
    warehouse_name: '倉庫名稱',
    product_name: '商品名稱',
    warehouse_id: '倉庫',
    product_id: '商品',
    quantity: '數量',
    safety_stock: '安全庫存',
    location: '儲位',
    // 庫存欄位
    batch_number: '批號',
    box_number: '箱號',
    origin_country: '來源國家',
    arrival_date: '入庫日期',
    expiry_date: '有效期限',
    source_purchase_order_id: '來源採購單',
    quality_status: '品質狀態',
    quality_remark: '品質備註',
    // 採購單欄位
    po_number: '採購單號',
    vendor_id: '廠商',
    vendor_name: '廠商名稱',
    user_name: '建單人員',
    user_id: '建單人員',
    total_amount: '小計',
    expected_delivery_date: '預計到貨日',
    status: '狀態',
    tax_amount: '稅額',
    grand_total: '總計',
    invoice_number: '發票號碼',
    invoice_date: '發票日期',
    invoice_amount: '發票金額',
    last_price: '供貨價格',
    // 公共事業費欄位
    transaction_date: '費用日期',
    category: '費用類別',
    amount: '金額',
};

// 採購單狀態對照表
const statusMap: Record<string, string> = {
    draft: '草稿',
    pending: '待審核',
    approved: '已核准',
    ordered: '已下單',
    received: '已收貨',
    cancelled: '已取消',
    completed: '已完成',
};

// 庫存品質狀態對照表
const qualityStatusMap: Record<string, string> = {
    normal: '正常',
    frozen: '凍結',
    rejected: '瑕疵/拒收',
};

export default function ActivityDetailDialog({ open, onOpenChange, activity }: Props) {
    if (!activity) return null;

    const attributes = activity.properties?.attributes || {};
    const old = activity.properties?.old || {};
    const snapshot = activity.properties?.snapshot || {};

    // 取得屬性和舊值的所有鍵，以確保顯示所有變更
    const allKeys = Array.from(new Set([...Object.keys(attributes), ...Object.keys(old)]));

    // 自訂欄位排序順序
    const sortOrder = [
        'po_number', 'vendor_name', 'warehouse_name', 'expected_delivery_date', 'status', 'remark',
        'invoice_number', 'invoice_date', 'invoice_amount',
        'total_amount', 'tax_amount', 'grand_total' // 確保金額的特定順序
    ];

    // 過濾掉通常會記錄但對使用者無用的內部鍵
    const filteredKeys = allKeys
        .filter(key =>
            !['created_at', 'updated_at', 'deleted_at', 'id', 'remember_token'].includes(key)
        )
        .sort((a, b) => {
            const indexA = sortOrder.indexOf(a);
            const indexB = sortOrder.indexOf(b);

            // 如果兩者都在排序順序中，比較索引
            if (indexA !== -1 && indexB !== -1) return indexA - indexB;
            // 如果只有 A 在排序順序中，它排在前面（或根據邏輯，通常將已知欄位排在前面）
            if (indexA !== -1) return -1;
            if (indexB !== -1) return 1;
            // 否則按字母順序或預設
            return a.localeCompare(b);
        });

    // 檢查鍵是否為快照名稱欄位的輔助函式
    const isSnapshotField = (key: string) => {
        return [
            'category_name', 'base_unit_name', 'large_unit_name', 'purchase_unit_name',
            'warehouse_name', 'user_name'
        ].includes(key);
    };

    const getEventBadgeClass = (event: string) => {
        switch (event) {
            case 'created': return 'bg-green-50 text-green-700 border-green-200';
            case 'updated': return 'bg-blue-50 text-blue-700 border-blue-200';
            case 'deleted': return 'bg-red-50 text-red-700 border-red-200';
            default: return 'bg-gray-50 text-gray-700 border-gray-200';
        }
    };

    const getEventLabel = (event: string) => {
        switch (event) {
            case 'created': return '新增';
            case 'updated': return '更新';
            case 'deleted': return '刪除';
            case 'updated_items': return '異動品項';
            default: return event;
        }
    };

    const formatValue = (key: string, value: any) => {
        // 遮蔽密碼
        if (key === 'password') return '******';

        if (value === null || value === undefined) return '-';
        if (typeof value === 'boolean') return value ? '是' : '否';
        if (key === 'is_active') return value ? '啟用' : '停用';

        // 處理採購單狀態
        if (key === 'status' && typeof value === 'string' && statusMap[value]) {
            return statusMap[value];
        }

        // 處理庫存品質狀態
        if (key === 'quality_status' && typeof value === 'string' && qualityStatusMap[value]) {
            return qualityStatusMap[value];
        }

        // 處理日期欄位 (YYYY-MM-DD)
        if ((key === 'expected_delivery_date' || key === 'invoice_date' || key === 'arrival_date' || key === 'expiry_date') && typeof value === 'string') {
            // 僅取日期部分 (YYYY-MM-DD)
            return value.split('T')[0].split(' ')[0];
        }

        return String(value);
    };

    const getFormattedValue = (key: string, value: any) => {
        // 如果是 ID 欄位，嘗試在快照或屬性中尋找對應名稱
        if (key.endsWith('_id')) {
            const nameKey = key.replace('_id', '_name');
            // 先檢查快照，然後檢查屬性
            const nameValue = snapshot[nameKey] || attributes[nameKey];
            if (nameValue) {
                return `${nameValue}`;
            }
        }
        return formatValue(key, value);
    };

    // 取得翻譯欄位標籤的輔助函式
    const getFieldLabel = (key: string) => {
        return fieldLabels[key] || key;
    };

    // 取得標題的主題名稱
    const getSubjectName = () => {
        // 庫存的特殊處理：顯示 "倉庫 - 商品"
        if ((snapshot.warehouse_name || attributes.warehouse_name) && (snapshot.product_name || attributes.product_name)) {
            const wName = snapshot.warehouse_name || attributes.warehouse_name;
            const pName = snapshot.product_name || attributes.product_name;
            return `${wName} - ${pName}`;
        }

        const nameParams = ['po_number', 'name', 'code', 'product_name', 'warehouse_name', 'category_name', 'base_unit_name', 'title'];
        for (const param of nameParams) {
            if (snapshot[param]) return snapshot[param];
            if (attributes[param]) return attributes[param];
            if (old[param]) return old[param];
        }

        if (attributes.id || old.id) return `#${attributes.id || old.id}`;
        return '';
    };

    const subjectName = getSubjectName();

    return (
        <Dialog open={open} onOpenChange={onOpenChange}>
            <DialogContent className="max-w-3xl max-h-[90vh] overflow-y-auto p-0 gap-0">
                <DialogHeader className="p-6 pb-4 border-b pr-12">
                    <div className="flex items-center gap-3 mb-2">
                        <DialogTitle className="text-xl font-bold text-gray-900">
                            操作詳情
                        </DialogTitle>
                        <Badge variant="outline" className={getEventBadgeClass(activity.event)}>
                            {getEventLabel(activity.event)}
                        </Badge>
                    </div>

                    {/* 現代化元數據條 */}
                    <div className="flex flex-wrap items-center gap-6 pt-2 text-sm text-gray-500">
                        <div className="flex items-center gap-2">
                            <User className="w-4 h-4 text-gray-400" />
                            <span className="font-medium text-gray-700">{activity.causer}</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <Clock className="w-4 h-4 text-gray-400" />
                            <span>{activity.created_at}</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <Package className="w-4 h-4 text-gray-400" />
                            <span className="font-medium text-gray-700">
                                {subjectName ? `${subjectName} ` : ''}
                                {activity.properties?.sub_subject || activity.subject_type}
                            </span>
                        </div>
                        {/* 僅在描述與事件名稱不同時顯示（不太可能發生但為了安全起見） */}
                        {activity.description !== getEventLabel(activity.event) &&
                            activity.description !== 'created' && activity.description !== 'updated' && (
                                <div className="flex items-center gap-2">
                                    <ActivityIcon className="w-4 h-4 text-gray-400" />
                                    <span>{activity.description}</span>
                                </div>
                            )}
                    </div>
                </DialogHeader>

                <div className="bg-gray-50/50 p-6 min-h-[300px]">
                    {activity.event === 'created' ? (
                        <div className="border rounded-md overflow-hidden bg-white shadow-sm">
                            <Table>
                                <TableHeader>
                                    <TableRow className="bg-gray-50/50 hover:bg-gray-50/50">
                                        <TableHead className="w-[150px]">欄位</TableHead>
                                        <TableHead>異動前</TableHead>
                                        <TableHead>異動後</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {filteredKeys
                                        .filter(key => attributes[key] !== null && attributes[key] !== '' && !isSnapshotField(key))
                                        .map((key) => (
                                            <TableRow key={key}>
                                                <TableCell className="font-medium text-gray-700 w-[150px]">{getFieldLabel(key)}</TableCell>
                                                <TableCell className="text-gray-500 break-words max-w-[200px]">-</TableCell>
                                                <TableCell className="text-gray-900 font-medium break-words max-w-[200px]">
                                                    {getFormattedValue(key, attributes[key])}
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    {filteredKeys.filter(key => attributes[key] !== null && attributes[key] !== '' && !isSnapshotField(key)).length === 0 && (
                                        <TableRow>
                                            <TableCell colSpan={3} className="h-24 text-center text-gray-500">
                                                無初始資料
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    ) : (
                        <div className="border rounded-md overflow-hidden bg-white shadow-sm">
                            <Table>
                                <TableHeader>
                                    <TableRow className="bg-gray-50 hover:bg-gray-50">
                                        <TableHead className="w-[150px]">欄位</TableHead>
                                        <TableHead>異動前</TableHead>
                                        <TableHead>異動後</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {filteredKeys.some(key => !isSnapshotField(key)) ? (
                                        filteredKeys
                                            .filter(key => {
                                                if (isSnapshotField(key)) return false;

                                                // 如果是更新事件，僅顯示有變動的欄位
                                                if (activity.event === 'updated') {
                                                    const oldValue = old[key];
                                                    const newValue = attributes[key];
                                                    return JSON.stringify(oldValue) !== JSON.stringify(newValue);
                                                }

                                                return true;
                                            })
                                            .map((key) => {
                                                const oldValue = old[key];
                                                const newValue = attributes[key];
                                                const isChanged = JSON.stringify(oldValue) !== JSON.stringify(newValue);

                                                // 對於刪除事件，我們希望在 "變更前" 欄位顯示當前屬性
                                                const displayBefore = activity.event === 'deleted'
                                                    ? getFormattedValue(key, newValue || oldValue)
                                                    : getFormattedValue(key, oldValue);

                                                const displayAfter = activity.event === 'deleted'
                                                    ? '-'
                                                    : getFormattedValue(key, newValue);

                                                return (
                                                    <TableRow key={key} className={isChanged ? 'bg-amber-50/30 hover:bg-amber-50/50' : 'hover:bg-gray-50/50'}>
                                                        <TableCell className="font-medium text-gray-700 w-[150px]">{getFieldLabel(key)}</TableCell>
                                                        <TableCell className="text-gray-500 break-words max-w-[200px]">
                                                            {displayBefore}
                                                        </TableCell>
                                                        <TableCell className="text-gray-900 font-medium break-words max-w-[200px]">
                                                            {displayAfter}
                                                        </TableCell>
                                                    </TableRow>
                                                );
                                            })
                                    ) : (
                                        <TableRow>
                                            <TableCell colSpan={3} className="h-24 text-center text-gray-500">
                                                無詳細異動內容
                                            </TableCell>
                                        </TableRow>
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    )}
                    {/* 項目差異區塊（採購單專用） */}
                    {activity.properties?.items_diff && (
                        <div className="mt-6 space-y-4">
                            <h3 className="text-sm font-bold text-gray-900 flex items-center gap-2 px-1">
                                <Package className="w-4 h-4 text-primary-main" />
                                品項異動明細
                            </h3>

                            <div className="border rounded-md overflow-hidden bg-white shadow-sm">
                                <Table>
                                    <TableHeader className="bg-gray-50/50">
                                        <TableRow>
                                            <TableHead>商品名稱</TableHead>
                                            <TableHead className="text-center">異動類型</TableHead>
                                            <TableHead>異動詳情 (舊 → 新)</TableHead>
                                        </TableRow>
                                    </TableHeader>
                                    <TableBody>
                                        {/* 更新項目 */}
                                        {activity.properties.items_diff.updated.map((item: any, idx: number) => (
                                            <TableRow key={`upd-${idx}`} className="bg-blue-50/10 hover:bg-blue-50/20">
                                                <TableCell className="font-medium">{item.product_name}</TableCell>
                                                <TableCell className="text-center">
                                                    <Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">更新</Badge>
                                                </TableCell>
                                                <TableCell className="text-sm">
                                                    <div className="space-y-1">
                                                        {item.old.quantity !== item.new.quantity && (
                                                            <div>數量: <span className="text-gray-500 line-through">{item.old.quantity}</span> → <span className="text-blue-700 font-bold">{item.new.quantity}</span></div>
                                                        )}
                                                        {item.old.unit_name !== item.new.unit_name && (
                                                            <div>單位: <span className="text-gray-500 line-through">{item.old.unit_name || '-'}</span> → <span className="text-blue-700 font-bold">{item.new.unit_name || '-'}</span></div>
                                                        )}
                                                        {item.old.subtotal !== item.new.subtotal && (
                                                            <div>小計: <span className="text-gray-500 line-through">${item.old.subtotal}</span> → <span className="text-blue-700 font-bold">${item.new.subtotal}</span></div>
                                                        )}
                                                    </div>
                                                </TableCell>
                                            </TableRow>
                                        ))}

                                        {/* 新增項目 */}
                                        {activity.properties.items_diff.added.map((item: any, idx: number) => (
                                            <TableRow key={`add-${idx}`} className="bg-green-50/10 hover:bg-green-50/20">
                                                <TableCell className="font-medium">{item.product_name}</TableCell>
                                                <TableCell className="text-center">
                                                    <Badge variant="outline" className="bg-green-50 text-green-700 border-green-200">新增</Badge>
                                                </TableCell>
                                                <TableCell className="text-sm">
                                                    數量: {item.quantity} {item.unit_name} / 小計: ${item.subtotal}
                                                </TableCell>
                                            </TableRow>
                                        ))}

                                        {/* 移除項目 */}
                                        {activity.properties.items_diff.removed.map((item: any, idx: number) => (
                                            <TableRow key={`rem-${idx}`} className="bg-red-50/10 hover:bg-red-50/20">
                                                <TableCell className="font-medium text-gray-400 line-through">{item.product_name}</TableCell>
                                                <TableCell className="text-center">
                                                    <Badge variant="outline" className="bg-red-50 text-red-700 border-red-200">移除</Badge>
                                                </TableCell>
                                                <TableCell className="text-sm text-gray-400">
                                                    原紀錄: {item.quantity} {item.unit_name}
                                                </TableCell>
                                            </TableRow>
                                        ))}
                                    </TableBody>
                                </Table>
                            </div>
                        </div>
                    )}
                </div>
            </DialogContent>
        </Dialog>
    );
}
