import { Tag, Typography, Flex } from 'antd';
import { forwardRef } from 'react';
import {
  CartesianGrid,
  Cell,
  Line,
  LineChart,
  Pie,
  PieChart,
  ResponsiveContainer,
  Tooltip,
  XAxis,
  YAxis,
} from 'recharts';
import { WidgetShell } from '../core';
import type { WidgetHandle } from '../core';
import { ProgressUI } from '../../components/dashboard/progress';
import { MultiProgressUI } from '../../components/dashboard/multiProgress';

const { Text, Title } = Typography;

export type ProgressListItem = {
  label: string;
  percent: number;
  color: string;
};

export type ProgressListGroup = {
  legend: string;
  items: ProgressListItem[];
};

export type LineChartPoint = {
  label: string;
  value: number;
};

export type MetricItem = {
  label: string;
  value: string;
};

export type SegmentedProgressItem = {
  label: string;
  percent: number;
  color: string;
};

export type DashboardReportSection =
  | {
      kind: 'progress-list';
      legend: string;
      title: string;
      items: ProgressListItem[];
    }
  | {
      kind: 'grouped-progress-list';
      legend: string;
      title: string;
      groups: [ProgressListGroup, ProgressListGroup];
    }
  | {
      kind: 'line-chart';
      legend: string;
      title: string;
      points: LineChartPoint[];
    }
  | {
      kind: 'metrics';
      legend: string;
      title: string;
      metrics: MetricItem[];
    }
  | {
      kind: 'segmented-progress';
      legend: string;
      title: string;
      segments: SegmentedProgressItem[];
    }
  | {
      kind: 'pie-chart';
      legend: string;
      title: string;
      totalLabel?: string;
      segments: SegmentedProgressItem[];
    };

export type DashboardReportCardWidgetProps = {
  id: string;
  title: string;
  moduleLabel?: string;
  sections: [DashboardReportSection, DashboardReportSection];
  sectionLayout?: 'vertical' | 'horizontal';
  cardWrapper?: boolean;
};

function ProgressListSection({ section }: { section: Extract<DashboardReportSection, { kind: 'progress-list' }> }) {
  return (
    <Flex vertical gap={12}>
      {section.items.map((item) => (
        <ProgressUI
          key={item.label}
          label={item.label}
          data={{
            percent: item.percent,
            color: item.color,
          }}
        />
      ))}
    </Flex>
  );
}

function LineChartSection({ section }: { section: Extract<DashboardReportSection, { kind: 'line-chart' }> }) {
  const chartData = section.points.map((point) => ({
    name: point.label,
    value: point.value,
  }));

  return (
    <Flex vertical gap={12}>
      <div className="dashboard-report__chart-shell">
        <ResponsiveContainer width="100%" height={190}>
          <LineChart
            data={chartData}
            margin={{ top: 12, right: 12, left: -8, bottom: 0 }}
          >
            <CartesianGrid strokeDasharray="3 3" stroke="rgba(24, 34, 48, 0.08)" />
            <XAxis
              dataKey="name"
              tickLine={false}
              axisLine={false}
              tick={{ fill: 'rgba(24, 34, 48, 0.62)', fontSize: 12 }}
            />
            <YAxis
              tickLine={false}
              axisLine={false}
              tick={{ fill: 'rgba(24, 34, 48, 0.62)', fontSize: 12 }}
              width={42}
            />
            <Tooltip
              cursor={{ stroke: 'rgba(22, 93, 255, 0.18)', strokeWidth: 1 }}
              contentStyle={{
                borderRadius: 12,
                border: '1px solid rgba(22, 93, 255, 0.12)',
                boxShadow: '0 16px 30px rgba(23, 61, 130, 0.08)',
              }}
            />
            <Line
              type="monotone"
              dataKey="value"
              stroke="#165dff"
              strokeWidth={3}
              dot={{ r: 4, fill: '#165dff', stroke: '#ffffff', strokeWidth: 2 }}
              activeDot={{ r: 6, fill: '#165dff', stroke: '#ffffff', strokeWidth: 2 }}
            />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </Flex>
  );
}

function GroupedProgressListSection({
  section,
}: {
  section: Extract<DashboardReportSection, { kind: 'grouped-progress-list' }>;
}) {
  return (
    <div className="dashboard-report__grouped-progress">
      {section.groups.map((group) => (
        <div key={group.legend} className="dashboard-report__grouped-column">
          <Tag color="blue" className="dashboard-report__grouped-badge">
            {group.legend}
          </Tag>
          <Flex vertical gap={10}>
            {group.items.map((item) => (
              <ProgressUI
                key={`${group.legend}-${item.label}`}
                label={item.label}
                data={{
                  percent: item.percent,
                  color: item.color,
                }}
              />
            ))}
          </Flex>
        </div>
      ))}
    </div>
  );
}

function MetricsSection({ section }: { section: Extract<DashboardReportSection, { kind: 'metrics' }> }) {
  return (
    <div className="dashboard-report__metrics">
      {section.metrics.map((metric) => (
        <div key={metric.label} className="dashboard-report__metric-item">
          <Text type="secondary">{metric.label}</Text>
          <Title level={4}>{metric.value}</Title>
        </div>
      ))}
    </div>
  );
}

function SegmentedProgressSection({
  section,
}: {
  section: Extract<DashboardReportSection, { kind: 'segmented-progress' }>;
}) {
  return (
    <MultiProgressUI label={section.title} meta={section.legend} data={section.segments} />
  );
}

function PieChartSection({ section }: { section: Extract<DashboardReportSection, { kind: 'pie-chart' }> }) {
  const totalPercent = section.segments.reduce((sum, segment) => sum + segment.percent, 0);

  return (
    <div className="dashboard-report__pie-layout">
      <div className="dashboard-report__chart-shell dashboard-report__chart-shell--pie">
        <ResponsiveContainer width="100%" height={220}>
          <PieChart>
            <Tooltip
              formatter={(value) => `${value ?? 0}%`}
              contentStyle={{
                borderRadius: 12,
                border: '1px solid rgba(22, 93, 255, 0.12)',
                boxShadow: '0 16px 30px rgba(23, 61, 130, 0.08)',
              }}
            />
            <Pie
              data={section.segments}
              dataKey="percent"
              nameKey="label"
              innerRadius={54}
              outerRadius={82}
              paddingAngle={2}
              stroke="#ffffff"
              strokeWidth={2}
            >
              {section.segments.map((segment) => (
                <Cell key={segment.label} fill={segment.color} />
              ))}
            </Pie>
          </PieChart>
        </ResponsiveContainer>
      </div>

      <Flex vertical gap={8}>
        {section.segments.map((segment) => (
          <div key={segment.label} className="dashboard-report__segment-legend">
            <span
              className="dashboard-report__segment-color"
              style={{ backgroundColor: segment.color }}
            />
            <Text>{segment.label}</Text>
            <Text className="dashboard-report__percent">{segment.percent}%</Text>
          </div>
        ))}

        <div className="dashboard-report__segment-legend dashboard-report__segment-legend--total">
          <span className="dashboard-report__segment-color dashboard-report__segment-color--total" />
          <Text strong>{section.totalLabel ?? '총재고'}</Text>
          <Text className="dashboard-report__percent">{totalPercent}%</Text>
        </div>
      </Flex>
    </div>
  );
}

function DashboardReportSectionView({ section }: { section: DashboardReportSection }) {
  return (
    <div className="dashboard-report__section">
      <Tag color="blue" className="dashboard-report__legend">
        {section.legend}
      </Tag>
      <Title level={5}>{section.title}</Title>
      <div className="dashboard-report__section-copy">
        {section.kind === 'progress-list' ? (
          <ProgressListSection section={section} />
        ) : section.kind === 'grouped-progress-list' ? (
          <GroupedProgressListSection section={section} />
        ) : section.kind === 'line-chart' ? (
          <LineChartSection section={section} />
        ) : section.kind === 'metrics' ? (
          <MetricsSection section={section} />
        ) : section.kind === 'pie-chart' ? (
          <PieChartSection section={section} />
        ) : (
          <SegmentedProgressSection section={section} />
        )}
      </div>
    </div>
  );
}

export const DashboardReportCardWidget = forwardRef<WidgetHandle, DashboardReportCardWidgetProps>(
  function DashboardReportCardWidget(
    { id, title, moduleLabel, sections, sectionLayout = 'vertical', cardWrapper },
    ref,
  ) {
    return (
      <WidgetShell
        ref={ref}
        id={id}
        title={title}
        cardWrapper={cardWrapper}
        features={['imperative-handle', 'feature-registry']}
        featureSlot={moduleLabel ? <Tag color="geekblue">{moduleLabel}</Tag> : undefined}
      >
        <div className={`dashboard-report dashboard-report--${sectionLayout}`}>
          {sections.map((section, index) => (
            <DashboardReportSectionView key={`${section.legend}-${index}`} section={section} />
          ))}
        </div>
      </WidgetShell>
    );
  },
);
