import React, { useState } from 'react';
import {
    Box,
    Paper,
    Table,
    TableBody,
    TableCell,
    TableContainer,
    TableHead,
    TableRow,
    Typography,
    Chip,
    Card,
    CardContent,
} from '@mui/material';
import {
    useReactTable,
    getCoreRowModel,
    createColumnHelper,
    flexRender,
} from '@tanstack/react-table';
import DescriptionIcon from '@mui/icons-material/Description';
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import CancelIcon from '@mui/icons-material/Cancel';
import CalendarTodayIcon from '@mui/icons-material/CalendarToday';

interface QCReport {
    id: string;
    productName: string;
    isQualified: boolean;
    remarks: string;
    reportDate: string;
    batchNumber: string;
    inspector: string;
    testResults: string;
    specifications: string;
}

interface QCReportFormProps {
    reports: QCReport[];
}

function QCReportForm({ reports }: QCReportFormProps): JSX.Element {
    const [selectedReport, setSelectedReport] = useState<QCReport | null>(null);

    const handleReportClick = (report: QCReport): void => {
        setSelectedReport(report);
    };

    const getQualifiedStatus = (isQualified: boolean) => {
        return isQualified ? (
            <Chip
                icon={<CheckCircleIcon />}
                label="合格"
                color="success"
                size="small"
                sx={{ fontWeight: 'medium' }}
            />
        ) : (
            <Chip
                icon={<CancelIcon />}
                label="不合格"
                color="error"
                size="small"
                sx={{ fontWeight: 'medium' }}
            />
        );
    };

    const columnHelper = createColumnHelper<QCReport>();

    const columns = [
        // columnHelper.accessor('productName', {
        //     header: '產品',
        //     cell: info => (
        //         <Typography variant="body2" fontWeight="medium">
        //             {info.getValue()}
        //         </Typography>
        //     ),
        // }),
        columnHelper.accessor('isQualified', {
            header: '合格',
            cell: info => getQualifiedStatus(info.getValue()),
        }),
        columnHelper.accessor('remarks', {
            header: '備註',
            cell: info => (
                <Typography
                    variant="body2"
                    color="text.secondary"
                    sx={{ maxWidth: '200px', overflow: 'hidden', textOverflow: 'ellipsis' }}
                >
                    {info.getValue()}
                </Typography>
            ),
        }),
        columnHelper.accessor('reportDate', {
            header: '上報日期',
            cell: info => (
                <Typography variant="body2" color="text.secondary">
                    {info.getValue()}
                </Typography>
            ),
        }),
    ];

    const table = useReactTable({
        data: reports,
        columns,
        getCoreRowModel: getCoreRowModel(),
    });

    return (
        <Box sx={{ maxWidth: '1200px', mx: 'auto', p: 3 }}>
            {/* Table Section */}
            <Box>
                <Typography variant="h6" fontWeight="medium" sx={{ mb: 2 }}>
                    上報資料
                </Typography>
                <TableContainer component={Paper} elevation={2}>
                    <Table>
                        <TableHead sx={{ bgcolor: 'grey.50' }}>
                            {table.getHeaderGroups().map(headerGroup => (
                                <TableRow key={headerGroup.id}>
                                    {headerGroup.headers.map(header => (
                                        <TableCell
                                            key={header.id}
                                            sx={{
                                                fontSize: '0.75rem',
                                                fontWeight: 'medium',
                                                color: 'text.secondary',
                                                textTransform: 'uppercase',
                                                py: 2,
                                                px: 3,
                                            }}
                                        >
                                            {header.isPlaceholder
                                                ? null
                                                : flexRender(header.column.columnDef.header, header.getContext())}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))}
                        </TableHead>
                        <TableBody>
                            {table.getRowModel().rows.map(row => (
                                <TableRow
                                    key={row.id}
                                    onClick={() => handleReportClick(row.original)}
                                    sx={{
                                        cursor: 'pointer',
                                        '&:hover': { bgcolor: 'grey.50' },
                                        bgcolor: selectedReport?.id === row.original.id ? 'primary.light' : 'inherit',
                                        transition: 'background-color 0.15s',
                                    }}
                                >
                                    {row.getVisibleCells().map(cell => (
                                        <TableCell key={cell.id} sx={{ py: 2, px: 3 }}>
                                            {flexRender(cell.column.columnDef.cell, cell.getContext())}
                                        </TableCell>
                                    ))}
                                </TableRow>
                            ))}
                        </TableBody>
                    </Table>
                </TableContainer>
            </Box>
        </Box>
    );
}

// Dummy data
const dummyReports = [
    {
        id: '1',
        productName: '無線藍牙耳機',
        isQualified: false,
        remarks: '包裝有破損',
        reportDate: '2024-08-06',
        batchNumber: 'WBE-240806-002',
        inspector: '李測試',
        testResults: '音質測試：左右聲道音量差異>3dB，不符合標準',
        specifications: '頻響範圍20Hz-20kHz，左右聲道音量差≤1dB，電池續航≥8小時',
    },
    {
        id: '2',
        productName: '筆記型電腦',
        isQualified: true,
        remarks: '經檢查，無損壞',
        reportDate: '2024-08-05',
        batchNumber: 'NB-240805-003',
        inspector: '王檢驗',
        testResults: '溫度測試：CPU最高溫度75°C，性能測試：符合預期',
        specifications: 'CPU溫度≤85°C，開機時間≤30秒，電池續航≥6小時',
    },
];

// Main component
function EscalationLog(): JSX.Element {
    return <QCReportForm reports={dummyReports} />;
};

export default EscalationLog;