import { Line, LineConfig } from '@ant-design/plots';
import React, { useState, useEffect } from 'react';
import { Card, DatePicker, Typography, Spin, message } from 'antd';
import axios from 'axios';
import moment from 'moment';

const { Title } = Typography;

interface VarietyYieldData {
  varietyName: string;
  yieldPercentage: number;
  soakInKgs: string;
  productionInKgs: string;
}

const VarietyYieldDashboard = () => {
  const aquaticColors = {
    primary: '#1E88E5',
    secondary: '#4DB6AC',
    accent: '#FF7043',
    lightBlue: '#E1F5FE',
    darkBlue: '#0D47A1',
    sand: '#FFF3E0',
    success: '#81C784',
    danger: '#EF5350',
    tableHeader: '#B3E5FC'
  };

  const [data, setData] = useState<VarietyYieldData[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedDate, setSelectedDate] = useState(moment().format('YYYY-MM-DD'));

  const fetchSoakingData = async (date: string) => {
    setLoading(true);
    try {
      const response = await axios.post(
        'http://localhost:6013/erpx/mainDashboard/getSoakingDataForProductionReport',
        { date }
      );

      if (response.data?.status) {
        const apiData = response.data.data;
        const products = apiData[1]?.product || [];
        const yieldPercentages = apiData[0]?.yieldPer || [];
        const soakInKgs = apiData[2]?.soakInKgs || [];
        const productionInKgs = apiData[3]?.productionInKgs || [];

        const transformedData = products.map((product: string, index: number) => ({
          varietyName: product,
          yieldPercentage: yieldPercentages[index] || 0,
          soakInKgs: soakInKgs[index] || "0.000",
          productionInKgs: productionInKgs[index] || "0.000"
        }));

        setData(transformedData);
      }
    } catch (error) {
      console.error('Error fetching soaking data:', error);
      message.error('Failed to load yield data');
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  const onDateChange = (date: moment.Moment | null, dateString: string) => {
    setSelectedDate(dateString);
    fetchSoakingData(dateString);
  };

  useEffect(() => {
    fetchSoakingData(selectedDate);
  }, []);

  const config: LineConfig = {
    data,
    xField: 'varietyName',
    yField: 'yieldPercentage',
    color: aquaticColors.primary,
    lineStyle: {
      lineWidth: 2,
    },
    point: {
      size: 4,
      shape: 'circle',
      style: {
        fill: aquaticColors.primary,
        stroke: '#fff',
        lineWidth: 2,
      },
    },
    yAxis: {
      min: -3000,
      max: 3000,
      title: { 
        text: 'Yield Percentage (%)', 
        style: { fill: '#666' } 
      },
      label: {
        formatter: (val: string) => `${val}%`,
      },
      grid: {
        line: {
          style: {
            stroke: '#eee',
            lineDash: [4, 4],
          },
        },
      },
    },
    xAxis: {
      title: {
        text: 'Variety Name',
        style: { fill: '#666' }
      },
      label: {
        autoRotate: true,
      }
    },
    tooltip: {
      showCrosshairs: true,
      customContent: (title: string, items: any[]) => {
        const varietyData = data.find(item => item.varietyName === title);
        if (!varietyData) return null;
        
        const formatPercentage = (value: number) => 
          value < 0 ? `-${Math.abs(value)}%` : `${value}%`;
        
        return (
          <div style={{ padding: '8px', background: '#fff' }}>
            <div style={{ fontWeight: 'bold', marginBottom: '8px' }}>Variety: {title}</div>
            <div style={{ color: varietyData.yieldPercentage < 0 ? aquaticColors.danger : aquaticColors.success }}>
              Yield: {formatPercentage(varietyData.yieldPercentage)}
            </div>
            <div>Soak Quantity: {varietyData.soakInKgs} KG</div>
            <div>Production: {varietyData.productionInKgs} KG</div>
          </div>
        );
      }
    },
  };

  return (
    <div style={{
      width: '100%',
      padding: '16px',
      boxSizing: 'border-box',
      display: 'flex',
      flexDirection: 'column',
      gap: '16px',
      background: aquaticColors.lightBlue,
      borderRadius: '8px',
      border: `1px solid ${aquaticColors.secondary}`
    }}>
      <Spin spinning={loading}>
        <Title
          level={3}
          style={{
            margin: 0,
            color: aquaticColors.darkBlue,
            textAlign: 'center',
            padding: '4px',
            backgroundColor: aquaticColors.tableHeader,
            borderRadius: '4px',
            fontSize: '18px'
          }}
        >
          Soaking Report
        </Title>

        <div style={{
          display: "flex",
          justifyContent: "flex-end",
          backgroundColor: aquaticColors.tableHeader,
          padding: '8px',
          borderRadius: '4px'
        }}>
          <DatePicker
            onChange={onDateChange}
            style={{ borderColor: aquaticColors.primary, width: '200px' }}
            defaultValue={moment(selectedDate)}
            format="YYYY-MM-DD"
          />
        </div>

        <Card
          title="Yield by Variety"
          headStyle={{
            backgroundColor: aquaticColors.secondary,
            color: 'white',
            borderTopLeftRadius: '8px',
            borderTopRightRadius: '8px',
            padding: '0 12px'
          }}
          bodyStyle={{
            padding: '12px',
            height: '500px',
          }}
          style={{
            borderRadius: '8px',
            borderColor: aquaticColors.secondary,
            boxShadow: '0 4px 8px rgba(0,0,0,0.1)',
            flex: 1
          }}
        >
          {data.length > 0 ? (
            <Line {...config} />
          ) : (
            <div style={{ 
              display: 'flex', 
              justifyContent: 'center', 
              alignItems: 'center', 
              height: '100%',
              color: aquaticColors.darkBlue
            }}>
              {loading ? 'Loading...' : 'No yield data available'}
            </div>
          )}
        </Card>
      </Spin>
    </div>
  );
};

export default VarietyYieldDashboard;