import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, useForm, router } from '@inertiajs/react';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from "@/Components/ui/table";
import { Button } from "@/Components/ui/button";
import { Input } from "@/Components/ui/input";
import { Badge } from "@/Components/ui/badge";
import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
    AlertDialogTrigger,
} from "@/Components/ui/alert-dialog";
import { Label } from "@/Components/ui/label";
import { Save, CheckCircle, Trash2, ArrowLeft, Plus, X, Search, ClipboardCheck } from "lucide-react";
import { useState, useEffect } from 'react';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from "@/Components/ui/dialog";
import axios from 'axios';
import { Can } from '@/Components/Permission/Can';

interface AdjItem {
    id?: string;
    product_id: string;
    product_name: string;
    product_code: string;
    batch_number: string | null;
    unit: string;
    qty_before: number;
    adjust_qty: number | string;
    notes: string;
}

interface AdjDoc {
    id: string;
    doc_no: string;
    warehouse_id: string;
    warehouse_name: string;
    status: string;
    reason: string;
    remarks: string;
    created_at: string;
    created_by: string;
    count_doc_id?: string;
    count_doc_no?: string;
    items: AdjItem[];
}

export default function Show({ doc }: { auth: any, doc: AdjDoc }) {
    const isDraft = doc.status === 'draft';

    // Main Form using Inertia useForm
    const { data, setData, put, delete: destroy, processing } = useForm({
        reason: doc.reason,
        remarks: doc.remarks || '',
        items: doc.items || [],
        action: 'save',
    });


    // Helper to add new item
    const addItem = (product: any, batchNumber: string | null) => {
        // Check if exists
        const exists = data.items.find(i =>
            i.product_id === String(product.id) &&
            i.batch_number === batchNumber
        );

        if (exists) {
            alert('此商品與批號已在列表中');
            return;
        }

        setData('items', [
            ...data.items,
            {
                product_id: String(product.id),
                product_name: product.name,
                product_code: product.code,
                unit: product.unit,
                batch_number: batchNumber,
                qty_before: product.qty || 0, // Not fetched dynamically for now, or could fetch via API
                adjust_qty: 0,
                notes: '',
            }
        ]);
    };

    const removeItem = (index: number) => {
        const newItems = [...data.items];
        newItems.splice(index, 1);
        setData('items', newItems);
    };

    const updateItem = (index: number, field: keyof AdjItem, value: any) => {
        const newItems = [...data.items];
        (newItems[index] as any)[field] = value;
        setData('items', newItems);
    };

    const handleSave = () => {
        setData('action', 'save');
        put(route('inventory.adjust.update', [doc.id]), {
            preserveScroll: true,
        });
    };

    const handlePost = () => {
        if (data.items.length === 0) {
            alert('請至少加入一個調整項目');
            return;
        }

        router.visit(route('inventory.adjust.update', [doc.id]), {
            method: 'put',
            data: { ...data, action: 'post' } as any,
        });
    };

    const handleDelete = () => {
        destroy(route('inventory.adjust.destroy', [doc.id]));
    };

    return (
        <AuthenticatedLayout
            breadcrumbs={[
                { label: '商品與庫存管理', href: '#' },
                { label: '庫存盤調', href: route('inventory.adjust.index') },
                { label: `盤調單: ${doc.doc_no}`, href: route('inventory.adjust.show', [doc.id]), isPage: true },
            ]}
        >
            <Head title={`盤調單 ${doc.doc_no}`} />

            <div className="container mx-auto p-6 max-w-7xl animate-in fade-in duration-500 space-y-6">
                <div>
                    <Link href={route('inventory.adjust.index')}>
                        <Button
                            variant="outline"
                            className="gap-2 button-outlined-primary mb-6"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            返回盤調單列表
                        </Button>
                    </Link>

                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                        <div>
                            <div className="flex items-center gap-2">
                                <h1 className="text-2xl font-bold text-grey-0 flex items-center gap-2">
                                    <ClipboardCheck className="h-6 w-6 text-primary-main" />
                                    盤調單: {doc.doc_no}
                                </h1>
                                {isDraft ? (
                                    <Badge variant="secondary" className="bg-gray-100 text-gray-600 border-none">草稿</Badge>
                                ) : (
                                    <Badge className="bg-green-100 text-green-700 border-none">已過帳</Badge>
                                )}
                            </div>
                            <p className="text-sm text-gray-500 mt-1 font-medium flex items-center gap-2">
                                倉庫: {doc.warehouse_name} <span className="mx-1">|</span>
                                建立者: {doc.created_by} <span className="mx-1">|</span>
                                時間: {doc.created_at}
                                {doc.count_doc_id && (
                                    <>
                                        <span className="mx-1">|</span>
                                        <Link
                                            href={route('inventory.count.show', [doc.count_doc_id])}
                                            className="flex items-center gap-1 text-primary-main hover:underline"
                                        >
                                            來源盤點單: {doc.count_doc_no}
                                        </Link>
                                    </>
                                )}
                            </p>
                        </div>
                        <div className="flex items-center gap-2">
                            {isDraft && (
                                <Can permission="inventory.adjust">
                                    <AlertDialog>
                                        <AlertDialogTrigger asChild>
                                            <Button variant="outline" size="sm" disabled={processing} className="button-outlined-error">
                                                <Trash2 className="w-4 h-4 mr-2" />
                                                刪除
                                            </Button>
                                        </AlertDialogTrigger>
                                        <AlertDialogContent>
                                            <AlertDialogHeader>
                                                <AlertDialogTitle>確定要刪除此盤調單嗎？</AlertDialogTitle>
                                                <AlertDialogDescription>
                                                    此動作將會永久移除本張草稿，且無法復原。
                                                </AlertDialogDescription>
                                            </AlertDialogHeader>
                                            <AlertDialogFooter>
                                                <AlertDialogCancel>取消</AlertDialogCancel>
                                                <AlertDialogAction onClick={handleDelete} className="bg-red-500 hover:bg-red-600">確認刪除</AlertDialogAction>
                                            </AlertDialogFooter>
                                        </AlertDialogContent>
                                    </AlertDialog>

                                    <Button
                                        variant="outline"
                                        size="sm"
                                        className="button-outlined-primary"
                                        onClick={handleSave}
                                        disabled={processing}
                                    >
                                        <Save className="w-4 h-4 mr-2" />
                                        儲存
                                    </Button>

                                    <Button
                                        size="sm"
                                        className="button-filled-primary"
                                        onClick={handlePost}
                                        disabled={processing}
                                    >
                                        <CheckCircle className="w-4 h-4 mr-2" />
                                        過帳
                                    </Button>
                                </Can>
                            )}
                        </div>
                    </div>
                </div>

                <div className="bg-white rounded-lg shadow-sm border p-6 space-y-4">
                    {/* Header Fields - Inline */}
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pb-2">
                        <div className="space-y-1">
                            <Label className="text-xs font-bold text-grey-500 uppercase tracking-wider">調整原因</Label>
                            {isDraft ? (
                                <Input
                                    value={data.reason}
                                    onChange={e => setData('reason', e.target.value)}
                                    className="focus:ring-primary-main h-9"
                                    placeholder="請輸入調整原因..."
                                />
                            ) : (
                                <div className="text-grey-900 font-medium py-1">{data.reason}</div>
                            )}
                        </div>
                        <div className="space-y-1">
                            <Label className="text-xs font-bold text-grey-500 uppercase tracking-wider">備註說明</Label>
                            {isDraft ? (
                                <Input
                                    value={data.remarks}
                                    onChange={e => setData('remarks', e.target.value)}
                                    className="focus:ring-primary-main h-9"
                                    placeholder="選填備註..."
                                />
                            ) : (
                                <div className="text-grey-600 py-1">{data.remarks || '-'}</div>
                            )}
                        </div>
                    </div>

                    <div className="border-t pt-4"></div>

                    <div className="flex flex-row items-center justify-between mb-2">
                        <h3 className="text-lg font-medium text-grey-900">調整項目</h3>
                        {isDraft && !doc.count_doc_id && (
                            <ProductSearchDialog
                                warehouseId={doc.warehouse_id}
                                onSelect={(product, batch) => addItem(product, batch)}
                            />
                        )}
                    </div>

                    <div className="border rounded-lg overflow-hidden">
                        <Table>
                            <TableHeader className="bg-gray-50">
                                <TableRow>
                                    <TableHead className="w-[50px] text-center font-medium text-grey-600">#</TableHead>
                                    <TableHead className="pl-4 font-medium text-grey-600">商品資訊</TableHead>
                                    <TableHead className="font-medium text-grey-600">批號</TableHead>
                                    <TableHead className="w-24 text-center font-medium text-grey-600">單位</TableHead>
                                    <TableHead className="w-32 text-right font-medium text-grey-600">調整前庫存</TableHead>
                                    <TableHead className="w-40 text-right font-medium text-grey-600">調整數量 (+/-)</TableHead>
                                    <TableHead className="font-medium text-grey-600">備註</TableHead>
                                    {isDraft && <TableHead className="w-[50px]"></TableHead>}
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {data.items.length === 0 ? (
                                    <TableRow>
                                        <TableCell colSpan={isDraft ? 8 : 7} className="h-32 text-center text-grey-400">
                                            尚未加入任何項目
                                        </TableCell>
                                    </TableRow>
                                ) : (
                                    data.items.map((item, index) => (
                                        <TableRow
                                            key={`${item.product_id}-${item.batch_number}-${index}`}
                                            className="group hover:bg-gray-50/50 transition-colors"
                                        >
                                            <TableCell className="text-center text-grey-400 font-medium">{index + 1}</TableCell>
                                            <TableCell className="pl-4 py-3">
                                                <div className="font-bold text-grey-900">{item.product_name}</div>
                                                <div className="text-xs text-grey-500 font-mono">{item.product_code}</div>
                                            </TableCell>
                                            <TableCell className="text-grey-600">{item.batch_number || '-'}</TableCell>
                                            <TableCell className="text-center text-grey-500">{item.unit}</TableCell>
                                            <TableCell className="text-right font-medium text-grey-400">
                                                {item.qty_before}
                                            </TableCell>
                                            <TableCell className="text-right">
                                                {isDraft ? (
                                                    <Input
                                                        type="number"
                                                        className="text-right h-9 border-grey-200 focus:ring-primary-main"
                                                        value={item.adjust_qty}
                                                        onChange={e => updateItem(index, 'adjust_qty', e.target.value)}
                                                    />
                                                ) : (
                                                    <span className={`font-bold ${Number(item.adjust_qty) > 0 ? 'text-green-600' : 'text-red-600'}`}>
                                                        {Number(item.adjust_qty) > 0 ? '+' : ''}{item.adjust_qty}
                                                    </span>
                                                )}
                                            </TableCell>
                                            <TableCell>
                                                {isDraft ? (
                                                    <Input
                                                        className="h-9 border-grey-200 focus:ring-primary-main text-sm"
                                                        value={item.notes || ''}
                                                        onChange={e => updateItem(index, 'notes', e.target.value)}
                                                        placeholder="備註..."
                                                    />
                                                ) : (
                                                    <span className="text-grey-600 text-sm">{item.notes || '-'}</span>
                                                )}
                                            </TableCell>
                                            {isDraft && !doc.count_doc_id && (
                                                <TableCell className="text-center">
                                                    <Button
                                                        variant="ghost"
                                                        size="sm"
                                                        className="h-8 w-8 text-red-400 hover:text-red-600 hover:bg-red-50 p-0"
                                                        onClick={() => removeItem(index)}
                                                    >
                                                        <X className="h-4 w-4" />
                                                    </Button>
                                                </TableCell>
                                            )}
                                        </TableRow>
                                    ))
                                )}
                            </TableBody>
                        </Table>
                    </div>
                </div>

            </div>
        </AuthenticatedLayout>
    );
}

// Simple internal component for product search
function ProductSearchDialog({ onSelect }: { warehouseId: string, onSelect: (p: any, b: string | null) => void }) {
    const [search, setSearch] = useState('');
    const [results, setResults] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);

    // Debounce search
    useEffect(() => {
        if (!search) {
            setResults([]);
            return;
        }
        const timer = setTimeout(() => {
            fetchProducts();
        }, 500);
        return () => clearTimeout(timer);
    }, [search]);

    const fetchProducts = async () => {
        setLoading(true);
        try {
            // Using existing API logic from Goods Receipts or creating a flexible one
            // Using count docs logic for now if specific endpoint not available, 
            // but `goods-receipts.search-products` is a good bet for general product search.
            const res = await axios.get(route('goods-receipts.search-products'), { params: { query: search } });
            setResults(res.data);
        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    return (
        <Dialog open={open} onOpenChange={setOpen}>
            <Button
                variant="outline"
                size="sm"
                className="h-8 border-primary-100 text-primary-main hover:bg-primary-50 px-3 flex items-center gap-2"
                onClick={() => setOpen(true)}
            >
                <Plus className="h-4 w-4" />
                新增調整項目
            </Button>
            <DialogContent className="sm:max-w-[500px] p-0 overflow-hidden border-none shadow-2xl">
                <DialogHeader className="bg-primary-main p-6">
                    <DialogTitle className="text-white text-xl flex items-center gap-2">
                        <Search className="h-5 w-5" />
                        搜尋並加入商品
                    </DialogTitle>
                </DialogHeader>
                <div className="p-6 space-y-4">
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-grey-400" />
                        <Input
                            placeholder="輸入商品名稱、代號或條碼..."
                            className="pl-11 h-12 border-grey-200 rounded-xl text-lg focus:ring-primary-main transition-all"
                            value={search}
                            onChange={e => setSearch(e.target.value)}
                            autoFocus
                        />
                    </div>

                    <div className="h-[350px] overflow-y-auto rounded-xl border border-grey-100 bg-grey-50">
                        {loading ? (
                            <div className="flex flex-col items-center justify-center h-full text-grey-400 space-y-3">
                                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-main"></div>
                                <span className="text-sm font-medium">搜尋中...</span>
                            </div>
                        ) : results.length === 0 ? (
                            <div className="flex flex-col items-center justify-center h-full text-grey-400 p-8 text-center space-y-2">
                                <Search className="h-10 w-10 opacity-20" />
                                <p className="text-sm">請輸入商品關鍵字開始搜尋</p>
                            </div>
                        ) : (
                            <div className="divide-y divide-grey-100">
                                {results.map(product => (
                                    <div
                                        key={product.id}
                                        className="p-4 hover:bg-white cursor-pointer flex justify-between items-center group transition-colors"
                                        onClick={() => {
                                            onSelect(product, null);
                                            setOpen(false);
                                            setSearch('');
                                            setResults([]);
                                        }}
                                    >
                                        <div className="space-y-1">
                                            <div className="font-bold text-grey-900 group-hover:text-primary-main transition-colors">{product.name}</div>
                                            <div className="text-xs text-grey-500 font-mono tracking-tight">{product.code}</div>
                                        </div>
                                        <div className="flex flex-col items-end gap-2">
                                            <Badge variant="outline" className="text-[10px] h-5 border-grey-200">{product.unit || '單位'}</Badge>
                                            <span className="text-[10px] text-grey-400">點擊加入</span>
                                        </div>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            </DialogContent>
        </Dialog>
    )
}
