import { Card, Col, DatePicker, Form, Row, Select, Tooltip } from "antd";
import React, { useEffect, useState } from "react";
import PaybleAndDueComponent from "./paybale-and-due-dasboard-compnet";
import PackingPayablesDashboard from "../packing-payables-dashboard";
import PackingVendorPay from "../packing-vendor-pay";
import GeneralVendorPay from "../general-vendor-pay";
import moment, { Moment } from "moment";
import { CalendarOutlined } from "@ant-design/icons";
import RMPayblesDashboard from "../rm-paybles-dashboard";
import SalesAmountAndNetWeight from "./sales-weight-and-amount-comonent";
import SoShippedCount from "./so-shipped-component";
import IncentiveTotalDashboard from "../incentive-total-dashboard";
import TotalIncentiveCollection from "../total-incentive-collection";
import RodtepReceivableDashboard from "../rodtep-receiveble-dashbord";
import DdbReceivableDashboard from "../ddb-receivable-dashbord";
import IgstReceivableDashboard from "../igst-receivable-dashboard";
import CollectionInvAmountVsBuyer from "./collection-inv-amount-vs-buyer-graph";
import CollectionInvOverdueAmountVsBuyer from "./collection-inv-overdue-vs-buyer-graph";
import OverDueReceivablesDashboard from "../over-due-receivables";
import SoPayablesDashboard from "../so-payables-dashboard";
import { CollectionsService, PurchasesProductService } from "@gtpl/shared-services/finance";
import { EndCustomersService } from "@gtpl/shared-services/masters";
import { GrnService } from "@gtpl/shared-services/procurement";
import Title from "antd/lib/typography/Title";
import { useForm } from "antd/lib/form/Form";

export default function SalesCeoDashboard() {
    const { RangePicker } = DatePicker;
        const [unitCodes,setUnitCodes]=useState([])
    const grnService = new GrnService()
         const {Option}=Select;
            const [unit,setUnit]=useState<any>();
            const [company,setCompany]=useState<any>()
    const [companyData,setCompanyData]=useState<any>()
    const collectionService=new CollectionsService()
         const currentYear = new Date().getFullYear();
         const [form]=useForm()
  const years = Array.from({ length: 20 }, (_, i) => currentYear - i);
  const months = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
  ];
        const [year,setYear]=useState<any>()
        const [month,setMonth]=useState<any>()
        const [buyerSelection,setBuyerSelection] = useState<boolean>(false)
    
         const initialRange: [Moment, Moment] = [
        moment().subtract(1, "days"),
        moment()
      ];

    const [dateRange, setDateRange] = useState<[Moment, Moment] | null>(initialRange);
    const colors = {
        primary: '#2D3A4B',
        secondary: '#4A90E2',
        accent: '#FF6B6B',
        background: '#F8F9FA',
        textSecondary: '#6C757D',
        success: '#28A745',
        warning: '#FFC107',
        headerBg: 'powderblue',
        headerText: '#FFFFFF',
        cardHover: '#F8F9FA'
    };

 const handleDateChange = (dates: [Moment, Moment], dateStrings: [string, string]) => {
        setDateRange(dates);
        setYear(null);   // reset year/month if user picks custom range
  setMonth(null);
   form.setFieldsValue({
    year: null,
    month: null,
  });
    };

    const handleYearChange = (value: number | null) => {
        setYear(value);
      setMonth(null); // reset month on year change
      const start = moment(`${value}-01-01`);
        const end = moment(`${value}-12-31`);
      setDateRange([start, end]); 
      if (!value) {
        setDateRange(initialRange);
      }
      };

       const handleMonthChange = (value: any) => {
              setMonth(value);
               if (year && value) {
          const start = moment(`${year}-${value}`, "YYYY-MM").startOf("month");
          const end = moment(`${year}-${value}`, "YYYY-MM").endOf("month");
          setDateRange([start, end]);   // update dateRange too
        }
          }

    // Extract formatted fromDate and toDate
      let fromDate: string | null = null;
    let toDate: string | null = null;
    
    if (year && month) {
      // Year + Month selected
      const startOfMonth = moment(`${year}-${month}`, "YYYY-MM").startOf("month");
      const endOfMonth = moment(`${year}-${month}`, "YYYY-MM").endOf("month");
      fromDate = startOfMonth.format("YYYY-MM-DD");
      toDate = endOfMonth.format("YYYY-MM-DD");
    } else if (year) {
      // Only Year selected
      fromDate = moment(`${year}-01-01`).format("YYYY-MM-DD");
      toDate = moment(`${year}-12-31`).format("YYYY-MM-DD");
    } else if (dateRange) {
      // No year → fall back to custom range
      fromDate = dateRange[0].format("YYYY-MM-DD");
      toDate = dateRange[1].format("YYYY-MM-DD");
    }
    // const fromDate = dateRange ? dateRange[0].format('YYYY-MM-DD') : null;
    // const toDate = dateRange ? dateRange[1].format('YYYY-MM-DD') : null;
    const [endCustomersData, setEndCustomersData] = useState<any[]>([]);
    const endCustomersService = new EndCustomersService();
    const [buyer,setBuyer]=useState<any>();

    console.log("dateRange", dateRange);

        useEffect(() => {
            getAllUnits()
            getAllEndCustomers()
            getCompanysForCeoDashboard()
        },[])

        const getCompanysForCeoDashboard = () => {
            collectionService.getCompanysForCeoDashboard().then((res) => {
                if (res.status) {
                    setCompanyData(res.data)
                }
            })
        }
    
        const getAllUnits = () => {
            grnService.getUnitsForCeoDashboard().then((res) => {
                if (res.status) {
                    setUnitCodes(res.data)
                }
            })
        }

        const getAllEndCustomers= () => {
            endCustomersService.getAllEndCustomers(null).then(res => {
              if (res.status) {
                setEndCustomersData(res.data);
              } else {
                if (res.intlCode) {
                  setEndCustomersData([]);
                } else {
                }
              }
            }).catch(err => {
              setEndCustomersData([]);
            })
          }
        const handleUnitChange = (value: any) => {
            setUnit(value);
        }

        const handleBuyerChange = (value: any) => {
            setBuyer(value);
            if(value > 0){
                setBuyerSelection(true)
            }else{
                setBuyerSelection(false)
            }
        }

        const handleCompanyChange = (value: any) => {
            setCompany(value);
        }

        const onBuyerHover = (buyerId) => {
            setBuyer(buyerId)
            
        }
    

    return (
        <>
         <Row gutter={24}>
                      <Col>
                            <Title level={3} style={{color: colors.primary }}>
                              Receivables Dashboard
                            </Title>
                          </Col>
                          </Row>
                          <br/>
                          <Form form={form}>
         <Row gutter={24}>
            <Col>
                <Tooltip title="Date range applies only to Stock In & Out">
                    <RangePicker
                        onChange={handleDateChange}
                        style={{ width: '100%', maxWidth: 230 }}
                        allowClear={false}
                        value={dateRange}
                        suffixIcon={<CalendarOutlined style={{ color: colors.textSecondary }} />}
                    />
                </Tooltip>
            </Col>
             <Col>
                    <Form.Item
                      name="year"
                      label="Year"
                      // rules={[{ required: true, message: "Please select year" }]}
                    >
                      <Select placeholder="Select Year" style={{ width: 120 }} allowClear
                        showSearch
                        optionFilterProp="children" onChange={handleYearChange}>
                        {years.map((year) => (
                          <Option key={year} value={year}>
                            {year}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
            
                  {/* Month Dropdown */}
                  <Col>
                    <Form.Item
                      name="month"
                      label="Month"
                      // rules={[{ required: true, message: "Please select month" }]}
                    >
                      <Select placeholder="Select Month" style={{ width: 150 }} allowClear
                        showSearch
                        optionFilterProp="children" onChange={(value)=>handleMonthChange(value)} disabled={!year}>
                        {months.map((month, idx) => (
                          <Option key={idx} value={idx + 1}>
                            {month}
                          </Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 7 }}>
                                    <Form.Item name="unitId" label="Unit">
                                        <Select
                                            placeholder="Select Unit"
                                            showSearch
                                            optionFilterProp="children"
                                            filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                            allowClear
                                            onChange={(val)=>handleUnitChange(val)}
                                            dropdownMatchSelectWidth ={false}

                                        >
                                           {unitCodes.map(dropData => {
                                                return <Option value={dropData.unitCodeId}>{dropData.plantCode}</Option>
                                            })}
                                        </Select>
                                    </Form.Item>
                                </Col>
                                </Row>
                                <Row gutter={24}>
                                 <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5}} lg={{ span: 5}} xl={{ span: 9}}>
                                                        <Form.Item name="companyId" label="Company">
                                                            <Select
                                                                placeholder="Select Company"
                                                                showSearch
                                                                optionFilterProp="children"
                                                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                                                allowClear
                                                                onChange={(val)=>handleCompanyChange(val)}
                                                                 dropdownMatchSelectWidth ={false}

                                                            >
                                                               {companyData?.map(dropData => {
                                                                    return <Option value={dropData.companyId}>{dropData.company}</Option>
                                                                })}
                                                            </Select>
                                                        </Form.Item>
                                                    </Col>
                                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5}} xl={{ span: 9 }}>
                                    <Form.Item name="buyerId" label="Buyer"
                                     >
                                        <Select
                                            placeholder="Select Buyer"
                                            showSearch
                                            optionFilterProp="children"
                                            filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                            allowClear
                                            onChange={(val)=>handleBuyerChange(val)}
                                            dropdownMatchSelectWidth ={false}
                                        >
                                           {endCustomersData.map(dropData => {
                                                return <Option value={dropData.endCustomerId}>{dropData.endCustomerName}</Option>
                                            })}
                                        </Select>
                                    </Form.Item>
                                </Col>
                                <Col>
                                <SoShippedCount fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                                </Col>
                                </Row>
                                </Form>
            <br />
            <Row gutter={24}>
                <Col span={16}>
                    <Row gutter={[0, 24]}>
                        <Col span={24}>
                            <CollectionInvAmountVsBuyer fromDate={fromDate} toDate={toDate} unit={unit} buyerId={buyerSelection ? buyer : undefined} division={company} onBuyerHover={onBuyerHover}/>
                        </Col>
                        <Col span={24}>
                            <CollectionInvOverdueAmountVsBuyer fromDate={fromDate} toDate={toDate} unit={unit} buyerId={buyerSelection ? buyer : undefined} division={company} onBuyerHover={onBuyerHover}/>
                        </Col>
                    </Row>
                </Col>
                <Col span={8}>
                    <Row gutter={[0, 24]}>
                        {/* <Col span={24}>
                        </Col> */}
                        <Col span={24}>
                            <OverDueReceivablesDashboard fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        <Col span={24}>
                            <SoPayablesDashboard fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        <Col span={24}>
                            <IncentiveTotalDashboard fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        <Col span={24}>
                            <TotalIncentiveCollection fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        <Col span={24}>
                            <RodtepReceivableDashboard fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        <Col span={24}>
                            <DdbReceivableDashboard fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        <Col span={24}>
                            <IgstReceivableDashboard fromDate={fromDate} toDate={toDate} unit={unit} buyer={buyer} company={company}/>
                        </Col>
                        
                           
                    </Row>
                </Col>
            </Row>
        </>
    )
}