"use client";
import IconTrashLines from '@/components/icon/icon-trash-lines';
import PanelCodeHighlight from '@/components/panel-code-highlight';
import ComponentsTablesSimple from '@/components/tables/components-tables-simple';
import { formatUnixTimestamp } from '@/utils/helpers';
import Tippy from '@tippyjs/react';
import axios from 'axios';
import React, { useEffect, useState } from 'react'

// import ReactApexChart from 'react-apexcharts';
import dynamic from 'next/dynamic';
import Link from 'next/link';
const ReactApexChart = dynamic(() => import('react-apexcharts'), { ssr: false });

type Props = {}

const SungrowInverters = (props: Props) => {
    const [inverters, setInverters] = useState<any[]>([])
    const [loading, setLoading] = useState(true)
    const [isMounted, setIsMounted] = useState(false)

    useEffect(() => {
        setIsMounted(true);
        const fetchData = async () => {
            try {
                const res = await axios.get("https://api-a.fomware.com.cn/asset/v1/list?type=2", {
                    headers: {
                        "Authorization": "Bearer " + process.env.NEXT_PUBLIC_CHINT_TOKEN
                    }
                })
                console.log("res", res.data.data.devices)
                setInverters(res.data.data.devices)
            } catch (error) {
                console.error("Error fetching data:", error);
            } finally {
                setLoading(false);
            }
        };

        fetchData()
    }, [])


    const chartConfigs: any = {
        options: {
            chart: {
                height: 58,
                type: 'line',
                fontFamily: 'Nunito, sans-serif',
                sparkline: {
                    enabled: true,
                },
                dropShadow: {
                    enabled: true,
                    blur: 3,
                    color: '#009688',
                    opacity: 0.4,
                },
            },
            stroke: {
                curve: 'smooth',
                width: 2,
            },
            colors: ['#009688'],
            grid: {
                padding: {
                    top: 5,
                    bottom: 5,
                    left: 5,
                    right: 5,
                },
            },
            tooltip: {
                x: {
                    show: false,
                },
                y: {
                    title: {
                        formatter: () => {
                            return '';
                        },
                    },
                },
            },
        },
    };

    // inverter status 0: initial, 1: standby, 2: fault, 3: running, 5: offline, 9: shutdown, 10: unknown

    return (
        <div>
            {loading ? <p>Loading...</p> : (
            <PanelCodeHighlight title="Chint Inverters">
                <div className="table-responsive mb-5">
                    <table>
                        <thead>
                            <tr>
                                <th>Inverter Name</th>
                                <th>Site Name</th>
                                <th>Gateway SN</th>
                                <th>Inverter Status</th>
                                <th>Model</th>
                                <th>SN</th>
                                <th>Real Time Power</th>
                                <th>E-Today</th>
                                <th>WeekData</th>
                                <th>Created At</th>
                                <th>Updated At</th>
                            </tr>
                        </thead>
                        <tbody>
                            {inverters.map((data) => (
                                <tr key={data.id}>
                                    <td>
                                        <div className="whitespace-nowrap"><Link href={`/chint/inverters/${data.name}`}>{data.name}</Link></div>
                                    </td>
                                    <td>
                                        <div className="whitespace-nowrap">{data.siteName}</div>
                                    </td>
                                    <td>
                                        <div>{data.gatewaySn}</div>
                                    </td>
                                    <td>
                                        <div className={`whitespace-nowrap ${
                                            data.status === 0 ? "text-gray-500"    // Initial
                                            : data.status === 1 ? "text-blue-500"  // Standby
                                            : data.status === 2 ? "text-red-500"  // Fault
                                            : data.status === 3 ? "text-green-500" // Running
                                            : data.status === 5 ? "text-yellow-500" // Offline
                                            : data.status === 9 ? "text-purple-500" // Shutdown
                                            : "text-gray-400" // Unknown (default)
                                        }`}>
                                            {data.statusLabel}
                                        </div>
                                    </td>
                                    <td>
                                        <div>{data.model}</div>
                                    </td>
                                    <td>
                                        <div>{data.sn}</div>
                                    </td>
                                    <td>
                                        <div>{data.activePowerWithUnit}</div>
                                    </td>
                                    <td>
                                        <div>{data.eTodayWithUnit}</div>
                                    </td>
                                    <td>
                                        {isMounted && (
                                            <ReactApexChart
                                                series={[{ data: data.weekTrend.map((point: any) => point.y) }]}
                                                options={{
                                                    ...chartConfigs.options,
                                                    xaxis: { categories: data.weekTrend.map((point: any) => point.x) },
                                                }}
                                                type="line"
                                                height={58}
                                                width={'100%'}
                                            />
                                        )}                                    </td>
                                    <td>{formatUnixTimestamp(data.createdAt)}</td>
                                    <td>{formatUnixTimestamp(data.updatedAt)}</td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                </div>
            </PanelCodeHighlight>
            )}
        </div>
    )
}

export default SungrowInverters
