import React, { useState, useCallback } from 'react';
import {
  Breadcrumb,
  Form,
  Grid,
  Select,
  Cascader,
  Input,
  Button,
  Space,
  Table,
  Card,
  Message,
  Dropdown,
  Menu,
  Checkbox,
  Modal,
  Upload,
} from '@arco-design/web-react';
import type { TableColumnProps } from '@arco-design/web-react/es/Table';
import {
  IconExport,
  IconImport,
  IconMore,
  IconSearch,
  IconRefresh,
} from '@arco-design/web-react/icon';
import {
  regionOptions,
  vehicleTypeOptions,
  brandOptions,
  modelOptions,
  customerOptions,
  businessDeptOptions,
  contractNoOptions,
  registeredOwnerOptions,
  mockVehicleList,
} from '@/services/vehicle';
import type { VehicleRecord, VehicleFilterForm } from '@/types/vehicle';
import VehiclePlateModal from './VehiclePlateModal';

const { Row, Col } = Grid;

const defaultFilter: VehicleFilterForm = {};

export default function VehicleManage() {
  const [filter, setFilter] = useState<VehicleFilterForm>(defaultFilter);
  const [plateNoQuick, setPlateNoQuick] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<VehicleRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [plateModalVisible, setPlateModalVisible] = useState(false);
  const [plateModalVehicle, setPlateModalVehicle] = useState<VehicleRecord | null>(null);
  const [form] = Form.useForm();

  const loadList = useCallback(
    (p = page, ps = pageSize) => {
      setLoading(true);
      setTimeout(() => {
        const res = mockVehicleList({
          ...filter,
          plateNo: plateNoQuick || undefined,
          page: p,
          pageSize: ps,
        });
        setData(res.list);
        setTotal(res.total);
        setLoading(false);
      }, 300);
    },
    [filter, plateNoQuick, page, pageSize]
  );

  React.useEffect(() => {
    loadList();
  }, [loadList]);

  const onFilterSubmit = (values: VehicleFilterForm) => {
    setFilter(values);
    setPage(1);
    loadList(1, pageSize);
  };

  const onFilterReset = () => {
    form.resetFields();
    setFilter(defaultFilter);
    setPlateNoQuick('');
    setPage(1);
    loadList(1, pageSize);
  };

  const onExport = () => {
    if (selectedRowKeys.length === 0) {
      Message.warning('请先勾选要导出的车辆');
      return;
    }
    Message.info(`导出 ${selectedRowKeys.length} 条记录（联调时对接导出接口）`);
  };

  const onBatchImport = () => {
    Message.info('批量导入（联调时对接导入接口）');
  };

  const onView = (record: VehicleRecord) => {
    Message.info(`查看车辆详情：${record.plateNo || record.vin}`);
    // 实际可： navigate(`/vehicle/detail/${record.id}`);
  };

  const onPlate = (record: VehicleRecord) => {
    setPlateModalVehicle(record);
    setPlateModalVisible(true);
  };

  const onPlateModalOk = (vin: string, plateNo: string) => {
    if (plateModalVehicle && (vin !== plateModalVehicle.vin || !plateNo)) {
      Message.error('车辆识别代号与该车辆不匹配');
      return;
    }
    Message.success('上牌信息已更新');
    setPlateModalVisible(false);
    setPlateModalVehicle(null);
    loadList();
  };

  const moreMenu = (record: VehicleRecord) => (
    <Menu>
      <Menu.Item key="plate" onClick={() => onPlate(record)}>车辆上牌</Menu.Item>
      <Menu.Item key="transfer">车辆过户</Menu.Item>
      <Menu.Item key="move">车辆异动</Menu.Item>
      <Menu.Item key="allocate">车辆调拨</Menu.Item>
      <Menu.Item key="scrap">车辆报废</Menu.Item>
      <Menu.Item key="inspect">车辆年审</Menu.Item>
      <Menu.Item key="sale">车辆出售</Menu.Item>
      <Menu.Item key="fault">故障提报</Menu.Item>
    </Menu>
  );

  const columns: TableColumnProps<VehicleRecord>[] = [
    { title: '运营城市', dataIndex: 'operationCity', width: 120, fixed: 'left' },
    { title: '车辆识别代号', dataIndex: 'vin', width: 180, fixed: 'left' },
    { title: '车牌号', dataIndex: 'plateNo', width: 100, fixed: 'left' },
    { title: '车辆编号', dataIndex: 'vehicleNo', width: 100, render: (v) => v || '-' },
    { title: '车辆类型', dataIndex: 'vehicleType', width: 100 },
    { title: '品牌', dataIndex: 'brand', width: 90 },
    { title: '型号', dataIndex: 'model', width: 90 },
    { title: '车身颜色', dataIndex: 'bodyColor', width: 90 },
    { title: '归属停车场', dataIndex: 'parkingLot', width: 110 },
    { title: '客户名称', dataIndex: 'customerName', width: 100 },
    { title: '业务部门', dataIndex: 'businessDept', width: 100 },
    { title: '业务负责人', dataIndex: 'businessOwner', width: 100 },
    { title: '运营状态', dataIndex: 'operationStatus', width: 90 },
    { title: '库位状态', dataIndex: 'libStatus', width: 180 },
    { title: '出库状态', dataIndex: 'outboundStatus', width: 100 },
    { title: '整备状态', dataIndex: 'prepStatus', width: 90 },
    { title: '过户状态', dataIndex: 'transferStatus', width: 120 },
    { title: '维修状态', dataIndex: 'repairStatus', width: 110 },
    { title: '证照状态', dataIndex: 'licenseStatus', width: 90 },
    { title: '报废状态', dataIndex: 'scrapStatus', width: 90 },
    { title: '登记所有权', dataIndex: 'registeredOwner', width: 160 },
    { title: '在线状态', dataIndex: 'onlineStatus', width: 90 },
    { title: '出厂年份', dataIndex: 'manufactureYear', width: 90 },
    { title: '行驶公里数(KM)', dataIndex: 'mileage', width: 120, render: (v) => v?.toFixed(2) ?? '-' },
    { title: '采购入库时间', dataIndex: 'purchaseTime', width: 120 },
    { title: '行驶证注册日期', dataIndex: 'licenseRegisterDate', width: 130 },
    { title: '行驶证检验有效期', dataIndex: 'licenseExpiry', width: 130 },
    { title: '上次交车时间', dataIndex: 'lastDeliveryTime', width: 120 },
    { title: '上次交车里程(KM)', dataIndex: 'lastDeliveryMileage', width: 130, render: (v) => (v ? Number(v).toFixed(2) : '-') },
    { title: '上次还车时间', dataIndex: 'lastReturnTime', width: 120 },
    { title: '上次还车里程(KM)', dataIndex: 'lastReturnMileage', width: 130, render: (v) => (v ? Number(v).toFixed(2) : '-') },
    { title: '强制报废日期', dataIndex: 'forceScrapDate', width: 120 },
    { title: '合同编号', dataIndex: 'contractNo', width: 110 },
    { title: '当前位置', dataIndex: 'currentLocation', width: 300 },
    { title: 'GPS最后上传时间', dataIndex: 'gpsLastTime', width: 160 },
    {
      title: '操作',
      dataIndex: 'op',
      width: 140,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button type="text" size="small" onClick={() => onView(record)}>
            查看
          </Button>
          <Dropdown trigger="hover" position="br" droplist={moreMenu(record)}>
            <Button type="text" size="small" icon={<IconMore />}>
              更多
            </Button>
          </Dropdown>
        </Space>
      ),
    },
  ];

  const watchedBrand = Form.useWatch('brand', form);
  const modelOptionsByBrand = watchedBrand ? (modelOptions as Record<string, { value: string; label: string }[]>)[watchedBrand] ?? [] : [];

  return (
    <div style={{ padding: 16, background: 'var(--color-fill-2)', minHeight: '100vh' }}>
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>运维管理</Breadcrumb.Item>
        <Breadcrumb.Item>车辆管理</Breadcrumb.Item>
      </Breadcrumb>

      <Card title="筛选" style={{ marginBottom: 16 }}>
        <Form
          form={form}
          layout="inline"
          initialValues={defaultFilter}
          onSubmit={onFilterSubmit}
          style={{ width: '100%' }}
        >
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="运营城市" field="operationCity">
                <Cascader
                  allowClear
                  placeholder="请选择省-市"
                  options={regionOptions}
                  style={{ width: '100%' }}
                  changeOnSelect
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="车辆类型" field="vehicleType">
                <Select allowClear placeholder="请选择" options={vehicleTypeOptions} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="品牌" field="brand">
                <Select allowClear placeholder="请选择" options={brandOptions} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="型号" field="model">
                <Select
                  allowClear
                  placeholder="请选择"
                  options={modelOptionsByBrand}
                  style={{ width: '100%' }}
                  disabled={!watchedBrand}
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="客户名称" field="customerName">
                <Select allowClear placeholder="请选择" options={customerOptions} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="归属业务部门" field="businessDept">
                <Select allowClear placeholder="请选择" options={businessDeptOptions} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="合同编号" field="contractNo">
                <Select
                  allowClear
                  showSearch
                  placeholder="输入模糊匹配"
                  options={contractNoOptions}
                  style={{ width: '100%' }}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="登记所有权" field="registeredOwner">
                <Select
                  allowClear
                  showSearch
                  placeholder="输入模糊匹配"
                  options={registeredOwnerOptions}
                  style={{ width: '100%' }}
                  filterOption={(input, option) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                  }
                />
              </Form.Item>
            </Col>
            <Col span={24}>
              <Form.Item style={{ marginBottom: 0 }}>
                <Space>
                  <Button type="primary" htmlType="submit" icon={<IconSearch />}>
                    查询
                  </Button>
                  <Button icon={<IconRefresh />} onClick={onFilterReset}>
                    重置
                  </Button>
                </Space>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>

      <Card>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <Space>
            <Input
              placeholder="输入车牌号快速筛选"
              value={plateNoQuick}
              onChange={setPlateNoQuick}
              style={{ width: 200 }}
              allowClear
              onPressEnter={() => loadList(1, pageSize)}
            />
            <Button type="primary" icon={<IconSearch />} onClick={() => { setPage(1); loadList(1, pageSize); }}>
              筛选
            </Button>
          </Space>
          <Space>
            <Button icon={<IconExport />} onClick={onExport}>
              导出（联动多选）
            </Button>
            <Button icon={<IconImport />} onClick={onBatchImport}>
              批量导入
            </Button>
          </Space>
        </div>

        <Table
          rowKey="id"
          loading={loading}
          data={data}
          columns={[
            {
              title: (
                <Checkbox
                  checked={selectedRowKeys.length === data.length && data.length > 0}
                  indeterminate={selectedRowKeys.length > 0 && selectedRowKeys.length < data.length}
                  onChange={(checked) => setSelectedRowKeys(checked ? data.map((r) => r.id) : [])}
                />
              ),
              width: 48,
              fixed: 'left',
              render: (_, record) => (
                <Checkbox
                  checked={selectedRowKeys.includes(record.id)}
                  onChange={(checked) =>
                    setSelectedRowKeys((prev) =>
                      checked ? [...prev, record.id] : prev.filter((k) => k !== record.id)
                    )
                  }
                />
              ),
            },
            ...columns,
          ]}
          scroll={{ x: 3800 }}
          pagination={{
            current: page,
            pageSize,
            total,
            showTotal: true,
            showJumper: true,
            sizeCanChange: true,
            pageSizeChange: (ps) => {
              setPageSize(ps);
              setPage(1);
              loadList(1, ps);
            },
            onChange: (p) => {
              setPage(p);
              loadList(p, pageSize);
            },
          }}
        />
      </Card>

      <VehiclePlateModal
        visible={plateModalVisible}
        vehicle={plateModalVehicle}
        onCancel={() => { setPlateModalVisible(false); setPlateModalVehicle(null); }}
        onOk={onPlateModalOk}
      />
    </div>
  );
}
