import { useEffect, useState, useMemo, useCallback } from 'react';
import {
  IconBrandAppleArcade,
  IconFile,
  IconVector,
  IconTrendingUp,
  IconSearch,
} from '@tabler/icons-react';
import {
  Button,
  TextField,
  Badge,
  CircleProgressBar,
  Tooltip,
  DatePicker,
  SelectDropdown,
  Table,
  Drawer,
  type Column,
  ButtonGroup,
  Avatar,
} from '@idds/react';
import type { FetchParams } from '@idds/react';
import { dashboardMetrics } from '../data/dashboardMetrics';
import {
  fetchDashboardTableDataNew,
  instansiFilterOptions,
  progressFilterOptions,
  statusFilterOptions,
  type DashboardTableRowNew,
} from '../data/tableDataNew';
import {
  defaultChartBarData,
  filterChartBarDataByPeriod,
  chartBarCategories,
} from '../data/chartBarData';

function getBrandColors(): string[] {
  return ['#A1C4F5', '#196BCD', '#0968F6', '#022A5B', '#041225', '#C0D7F9'];
}

const iconMap = {
  package: IconBrandAppleArcade,
  document: IconFile,
  'check-square': IconVector,
};

// Helper untuk mendapatkan warna badge status
const getStatusBadgeVariant = (
  status: DashboardTableRowNew['status'],
): 'success' | 'error' | 'warning' | 'neutral' => {
  switch (status) {
    case 'Sangat Baik':
      return 'success';
    case 'Baik':
      return 'neutral';
    case 'Cukup':
      return 'warning';
    case 'Kurang':
      return 'error';
    default:
      return 'neutral';
  }
};

// Helper untuk mendapatkan warna progress
const getProgressColor = (progress: number): string => {
  if (progress >= 76) return 'text-green-600';
  if (progress >= 51) return 'text-blue-600';
  if (progress >= 26) return 'text-orange-600';
  return 'text-red-600';
};

const getInitials = (name: string) => {
  return name
    .split(' ')
    .map((word) => word[0])
    .join('')
    .slice(0, 2)
    .toUpperCase();
};

// Table columns configuration moved inside component to access handlers

export default function Dashboard() {
  const [ReactApexChartComponent, setReactApexChartComponent] =
    useState<any>(null);
  const [brandColors, setBrandColors] = useState<string[]>([]);
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [selectedDate, setSelectedDate] = useState<string | null>(null);
  const [selectedPeriod, setSelectedPeriod] = useState<string | number>(
    '1-bulan',
  );
  const [searchTerm, setSearchTerm] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string | null>(null);
  const [progressFilter, setProgressFilter] = useState<string | null>(null);
  const [instansiFilter, setInstansiFilter] = useState<string | null>(null);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [selectedRow, setSelectedRow] = useState<DashboardTableRowNew | null>(
    null,
  );

  const handleDetailClick = (row: DashboardTableRowNew) => {
    setSelectedRow(row);
    setIsDrawerOpen(true);
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      import('react-apexcharts').then((module) => {
        setReactApexChartComponent(() => module.default);
      });

      // Initialize brand colors
      const colors = getBrandColors();
      setBrandColors(colors);
    }
  }, []);

  // Filter chart data berdasarkan periode
  const chartBarData = useMemo(() => {
    return filterChartBarDataByPeriod(
      defaultChartBarData,
      selectedPeriod as '1-tahun' | '1-bulan' | '7-hari',
    );
  }, [selectedPeriod]);

  const chartBarSeries = useMemo(
    () => [
      {
        name: 'Adopsi',
        data: chartBarData.map((point) => point.value),
      },
    ],
    [chartBarData],
  );

  const chartBarOptions = useMemo(
    () => ({
      chart: {
        id: 'dashboard-bar-chart',
        type: 'bar',
        toolbar: { show: false },
      },
      xaxis: {
        categories: chartBarCategories,
      },
      yaxis: {
        labels: {
          formatter: (val: number) => `${val}x`,
        },
      },
      plotOptions: {
        bar: {
          borderRadius: 4,
          columnWidth: '60%',
          distributed: true,
        },
      },
      dataLabels: {
        enabled: false,
      },
      colors: brandColors.length > 0 ? brandColors : ['#3b82f6'],
      legend: {
        show: true,
        position: 'bottom',
        showForSingleSeries: true,
      },
    }),
    [chartBarData, brandColors],
  ) as any;

  // Fetch function untuk table dengan filters
  const fetchData = useCallback(
    (params: FetchParams) => {
      return fetchDashboardTableDataNew({
        ...params,
        searchTerm: searchTerm || params.searchTerm, // Use local searchTerm state
        statusFilter,
        progressFilter,
        instansiFilter,
      });
    },
    [searchTerm, statusFilter, progressFilter, instansiFilter],
  );

  // Convert date format dari dd/MM/yyyy ke YYYY-MM-DD
  const convertToISO = (dateStr: string): string => {
    if (!dateStr) return '';
    const parts = dateStr.split('/');
    if (parts.length === 3) {
      return `${parts[2]}-${parts[1]}-${parts[0]}`;
    }
    return dateStr;
  };

  // Convert date format dari YYYY-MM-DD ke dd/MM/yyyy
  const convertToDisplay = (dateStr: string): string => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    const day = String(date.getDate()).padStart(2, '0');
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const year = date.getFullYear();
    return `${day}/${month}/${year}`;
  };

  const handleDateRangeChange = useCallback((range: [string, string]) => {
    const isoRange: [string, string] = [
      convertToISO(range[0]),
      convertToISO(range[1]),
    ];
    setDateRange(isoRange);
  }, []);

  const handleDateChange = useCallback((date: string) => {
    setSelectedDate(date ? convertToISO(date) : null);
  }, []);

  // Convert dateRange ke display format untuk DatePicker
  const dateRangeDisplay = useMemo(() => {
    if (!dateRange || !dateRange[0] || !dateRange[1]) {
      return ['', ''] as [string, string];
    }
    return [convertToDisplay(dateRange[0]), convertToDisplay(dateRange[1])] as [
      string,
      string,
    ];
  }, [dateRange]);

  const dateDisplay = useMemo(() => {
    if (!selectedDate) return '';
    return convertToDisplay(selectedDate);
  }, [selectedDate]);

  // Status options untuk filter
  const statusOptions = statusFilterOptions;
  const progressOptions = progressFilterOptions;
  const instansiOptions = instansiFilterOptions;

  // ButtonGroup options untuk periode
  const periodOptions = [
    { value: '1-tahun', label: '1 Tahun' },
    { value: '1-bulan', label: '1 Bulan' },
    { value: '7-hari', label: '7 Hari' },
  ];

  // Table columns configuration
  const tableColumnsConfig: Column[] = useMemo(
    () => [
      {
        header: 'Nama',
        accessor: 'name',
        sortable: true,
        render: (row: DashboardTableRowNew) => (
          <div className="flex items-center gap-3 text-xs">
            <Avatar
              src={row.logo}
              alt={row.name}
              size={32}
              initials={getInitials(row.name)}
            />
            <div className="flex flex-col max-w-[96px] sm:max-w-none">
              <div
                className="font-medium text-content-primary truncate"
                title={row.fullName}
              >
                {row.name}
              </div>
              {row.nameSubtext && (
                <div
                  className="text-[10px] sm:text-xs text-gray-500 truncate max-w-[120px]"
                  title={row.nameSubtext}
                >
                  {row.nameSubtext}
                </div>
              )}
            </div>
          </div>
        ),
      },
      {
        header: 'Progress',
        accessor: 'progress',
        sortable: true,
        render: (row: DashboardTableRowNew) => {
          let variant = 'negative';
          if (row.progress >= 76) variant = 'positive';
          else if (row.progress >= 51) variant = 'primary';
          else if (row.progress >= 26) variant = 'warning';

          return (
            <div className="flex items-center gap-2 pl-4 sm:pl-0">
              <CircleProgressBar
                progress={row.progress}
                diameter={20}
                strokeWidth={3}
                variant={variant}
              />
              <span
                className={`text-xs font-medium ${getProgressColor(row.progress)}`}
              >
                {row.progress}%
              </span>
            </div>
          );
        },
      },
      {
        header: 'Status',
        accessor: 'status',
        sortable: true,
        render: (row: DashboardTableRowNew) => (
          <Badge
            variant={getStatusBadgeVariant(row.status)}
            type="soft"
            size="sm"
          >
            {row.status}
          </Badge>
        ),
      },
      {
        header: 'Estimasi Efisiensi',
        accessor: 'estimasiEfisiensi',
        sortable: true,
        render: (row: DashboardTableRowNew) => (
          <span className="text-sm text-gray-700">{row.estimasiEfisiensi}</span>
        ),
      },
      {
        header: 'Aksi',
        accessor: 'actions',
        sortable: false,
        render: (row: DashboardTableRowNew) => (
          <Tooltip title="Lihat Detail" placement="top">
            <Button
              hierarchy="secondary"
              size="sm"
              onClick={() => handleDetailClick(row)}
            >
              Lihat Detail
            </Button>
          </Tooltip>
        ),
      },
    ],
    [],
  );

  return (
    <div className="space-y-6">
      {/* Header Section */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
          <h1 className="text-xl md:text-2xl font-semibold text-content-primary">
            Dashboard
          </h1>
          <p className="text-sm text-content-secondary mt-1">
            Ringkasan pertumbuhan penggunaan komponen di berbagai kategori
            antarmuka.
          </p>
        </div>
        <DatePicker
          mode="range"
          selected={dateRangeDisplay}
          onChange={handleDateRangeChange}
          placeholder="Pilih Rentang Tanggal"
          dateFormat="dd/MM/yyyy"
          triggerWidth="250px"
          size="sm"
        />
      </div>

      {/* Metrics Cards */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {dashboardMetrics.map((metric) => {
          const IconComponent =
            iconMap[metric.icon as keyof typeof iconMap] ||
            IconBrandAppleArcade;
          const iconColorClass =
            metric.iconColor === 'orange'
              ? 'bg-orange-500 text-white'
              : metric.iconColor === 'blue'
                ? 'bg-guide-500 text-white'
                : metric.iconColor === 'green'
                  ? 'bg-positive-600 text-white'
                  : 'bg-negative-600 text-white';

          return (
            <div
              key={metric.label}
              className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm"
            >
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <p className="text-sm text-content-secondary mb-1">
                    {metric.label}
                  </p>
                  <p className="text-3xl font-semibold text-content-primary mb-2">
                    {metric.value}
                  </p>
                  <div className="flex items-center space-x-2">
                    <IconTrendingUp size={20} className="text-green-600" />
                    <span className="text-xs text-green-600">
                      {metric.subtitle}
                    </span>
                  </div>
                </div>
                <div className={`p-2 md:p-3 rounded-lg ${iconColorClass}`}>
                  <IconComponent size={24} />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Chart Section */}
      <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
        <div className="mb-6">
          <h2 className="text-lg font-semibold text-content-primary mb-1">
            Tren Adopsi Komponen Per Kategori
          </h2>
        </div>
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
          <ButtonGroup
            options={periodOptions}
            value={selectedPeriod}
            onChange={(value) => setSelectedPeriod(value)}
          />
          <DatePicker
            mode="single"
            selected={dateDisplay}
            onChange={handleDateChange}
            placeholder="Pilih Tanggal"
            dateFormat="dd/MM/yyyy"
            triggerWidth="200px"
            size="sm"
          />
        </div>
        {ReactApexChartComponent ? (
          <ReactApexChartComponent
            key={`bar-chart-${selectedPeriod}`}
            type="bar"
            height={350}
            series={chartBarSeries}
            options={chartBarOptions}
          />
        ) : (
          <div className="h-[350px] flex items-center justify-center text-gray-500">
            Loading chart...
          </div>
        )}
      </div>

      {/* Table Section */}
      <div className="bg-white rounded-lg border border-gray-200 p-6 shadow-sm">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-4">
          <TextField
            value={searchTerm}
            onChange={(val) => setSearchTerm(val)}
            placeholder="Search..."
            prefixIcon={<IconSearch size={16} />}
            className="flex-1 max-w-md"
          />
          <div className="flex flex-wrap items-center gap-2 w-full lg:max-w-[60%]">
            <SelectDropdown
              options={statusOptions}
              selected={statusFilter}
              onSelect={(value) =>
                setStatusFilter(value === 'all' ? null : value)
              }
              placeholder="Status"
              size="sm"
              className="flex-1"
            />
            <SelectDropdown
              options={progressOptions}
              selected={progressFilter}
              onSelect={(value) =>
                setProgressFilter(value === 'all' ? null : value)
              }
              placeholder="Progress"
              size="sm"
              className="flex-1"
            />
            <SelectDropdown
              options={instansiOptions}
              selected={instansiFilter}
              onSelect={(value) =>
                setInstansiFilter(value === 'all' ? null : value)
              }
              placeholder="Instansi"
              size="sm"
              className="flex-1"
            />
          </div>
        </div>
        <Table
          columns={tableColumnsConfig}
          fetchData={fetchData}
          initialPageSize={10}
          pageSizeOptions={[10, 20, 30, 50]}
          showSearch={false}
          rowKey="id"
          selectable={true}
        />
      </div>
      <Drawer
        isOpen={isDrawerOpen}
        onClose={() => setIsDrawerOpen(false)}
        title={selectedRow?.fullName || 'Detail Instansi'}
        position="right"
        width="md"
      >
        {selectedRow && (
          <div className="space-y-6">
            <div className="flex items-center gap-4">
              {selectedRow.logo && (
                <img
                  src={selectedRow.logo}
                  alt={selectedRow.name}
                  className="w-16 h-16 rounded-full"
                />
              )}
              <div>
                <h3 className="text-lg font-semibold text-content-primary">
                  {selectedRow.fullName}
                </h3>
                {selectedRow.nameSubtext && (
                  <p className="text-sm text-gray-500">
                    {selectedRow.nameSubtext}
                  </p>
                )}
              </div>
            </div>

            <div className="grid grid-cols-2 gap-4">
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-xs text-content-secondary mb-1">Status</p>
                <Badge
                  variant={getStatusBadgeVariant(selectedRow.status)}
                  type="soft"
                  size="md"
                >
                  {selectedRow.status}
                </Badge>
              </div>
              <div className="p-4 bg-gray-50 rounded-lg">
                <p className="text-xs text-content-secondary mb-1">Progress</p>
                <div className="flex items-center gap-2">
                  <span className="text-xl font-semibold">
                    {selectedRow.progress}%
                  </span>
                </div>
              </div>
              <div className="col-span-2 p-4 bg-gray-50 rounded-lg">
                <p className="text-xs text-content-secondary mb-1">
                  Estimasi Efisiensi
                </p>
                <p className="text-xl font-semibold text-content-primary">
                  {selectedRow.estimasiEfisiensi}
                </p>
              </div>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
}
