import { useState, useMemo } from 'react';
import {
  Typography,
  Button,
  Card,
  Table,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  AutoComplete,
  Alert,
  Drawer,
  Descriptions,
  Popconfirm,
  Row,
  Col,
  Statistic,
  Switch,
  Skeleton,
} from 'antd';
import { showSuccess, showError } from '@/lib/errorHandling';
import {
  PlusOutlined,
  EditOutlined,
  SearchOutlined,
  EyeOutlined,
  StopOutlined,
  CheckOutlined,
  ShoppingOutlined,
} from '@ant-design/icons';
import { useCompany } from '@/hooks/useCompany';
import { useProducts, useManufacturers, type Product } from '@/api/queries/productQueries';
import {
  useCreateProduct,
  useUpdateProduct,
  useDeactivateProduct,
  useReactivateProduct,
  type CreateProductInput,
  type UpdateProductInput,
} from '@/api/mutations/productMutations';
import { formatDate, formatCurrency } from '@/lib/formatters';
import { spacing } from '@/styles/designTokens';
import { StatusBadge } from '@/components/shared/StatusBadge';
import { EmptyState } from '@/components/shared/EmptyState';
import { PageHeader } from '@/components/shared/PageHeader';
import type { ColumnsType } from 'antd/es/table';

const { Text } = Typography;

// VAT code options
const vatCodeOptions = [
  { value: 'U25', label: 'Udgående moms 25% (U25)' },
  { value: 'UEU', label: 'EU-salg uden moms (UEU)' },
  { value: 'UEXP', label: 'Eksport uden moms (UEXP)' },
  { value: 'INGEN', label: 'Ingen moms (INGEN)' },
];

// Common unit options
const unitOptions = [
  { value: 'stk', label: 'stk' },
  { value: 'time', label: 'time' },
  { value: 'dag', label: 'dag' },
  { value: 'måned', label: 'måned' },
  { value: 'kg', label: 'kg' },
  { value: 'm', label: 'm' },
  { value: 'm2', label: 'm2' },
  { value: 'm3', label: 'm3' },
  { value: 'l', label: 'l' },
  { value: 'pakke', label: 'pakke' },
];

export default function Produkter() {
  const { company } = useCompany();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [searchText, setSearchText] = useState('');
  const [showInactive, setShowInactive] = useState(false);
  const [manufacturerSearch, setManufacturerSearch] = useState('');
  const [form] = Form.useForm();

  // Fetch products using the new hook
  const {
    data: products = [],
    isLoading: loading,
    error,
  } = useProducts(company?.id);

  // Fetch manufacturers for autocomplete
  const { data: manufacturers = [] } = useManufacturers(company?.id, manufacturerSearch);

  // Mutations using new hooks
  const createProductMutation = useCreateProduct();
  const updateProductMutation = useUpdateProduct();
  const deactivateProductMutation = useDeactivateProduct();
  const reactivateProductMutation = useReactivateProduct();

  // Filter products
  const filteredProducts = useMemo(() => {
    return products.filter((product) => {
      const searchLower = searchText.toLowerCase();
      const matchesSearch =
        searchText === '' ||
        product.name.toLowerCase().includes(searchLower) ||
        (product.productNumber && product.productNumber.includes(searchText)) ||
        (product.description && product.description.toLowerCase().includes(searchLower)) ||
        (product.ean && product.ean.includes(searchText)) ||
        (product.manufacturer && product.manufacturer.toLowerCase().includes(searchLower));

      const matchesStatus = showInactive || product.isActive;

      return matchesSearch && matchesStatus;
    });
  }, [products, searchText, showInactive]);

  // Statistics
  const stats = useMemo(() => {
    const active = products.filter((p) => p.isActive).length;
    const totalValue = products
      .filter((p) => p.isActive)
      .reduce((sum, p) => sum + p.unitPrice, 0);
    return { total: products.length, active, totalValue };
  }, [products]);

  const handleCreate = () => {
    setEditingProduct(null);
    form.resetFields();
    form.setFieldsValue({ vatCode: 'U25', unitPrice: 0, unit: 'stk' });
    setIsModalOpen(true);
  };

  const handleEdit = (product: Product) => {
    setEditingProduct(product);
    form.setFieldsValue({
      productNumber: product.productNumber,
      name: product.name,
      description: product.description,
      unitPrice: product.unitPrice,
      vatCode: product.vatCode,
      unit: product.unit,
      ean: product.ean,
      manufacturer: product.manufacturer,
    });
    setIsModalOpen(true);
  };

  const handleView = (product: Product) => {
    setSelectedProduct(product);
    setIsDrawerOpen(true);
  };

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      if (editingProduct) {
        const input: UpdateProductInput = {
          id: editingProduct.id,
          productNumber: values.productNumber || undefined,
          name: values.name,
          description: values.description || undefined,
          unitPrice: values.unitPrice,
          vatCode: values.vatCode,
          unit: values.unit || undefined,
          ean: values.ean || undefined,
          manufacturer: values.manufacturer || undefined,
        };
        await updateProductMutation.mutateAsync(input);
        showSuccess('Produkt opdateret');
      } else {
        const input: CreateProductInput = {
          companyId: company!.id,
          productNumber: values.productNumber || undefined,
          name: values.name,
          description: values.description || undefined,
          unitPrice: values.unitPrice,
          vatCode: values.vatCode,
          unit: values.unit || undefined,
          ean: values.ean || undefined,
          manufacturer: values.manufacturer || undefined,
        };
        await createProductMutation.mutateAsync(input);
        showSuccess('Produkt oprettet');
      }
      setIsModalOpen(false);
      setEditingProduct(null);
      form.resetFields();
    } catch (err) {
      if (err instanceof Error) {
        showError(err);
      }
    }
  };

  const handleToggleActive = async (product: Product) => {
    try {
      if (product.isActive) {
        await deactivateProductMutation.mutateAsync(product.id);
        showSuccess('Produkt deaktiveret');
      } else {
        await reactivateProductMutation.mutateAsync(product.id);
        showSuccess('Produkt genaktiveret');
      }
    } catch (err) {
      if (err instanceof Error) {
        showError(err);
      }
    }
  };

  const columns: ColumnsType<Product> = [
    {
      title: 'Produktnr.',
      dataIndex: 'productNumber',
      key: 'productNumber',
      width: 120,
      sorter: (a, b) => (a.productNumber || '').localeCompare(b.productNumber || ''),
      render: (value: string) => value ? <Text code>{value}</Text> : <Text type="secondary">-</Text>,
    },
    {
      title: 'Navn',
      dataIndex: 'name',
      key: 'name',
      sorter: (a, b) => a.name.localeCompare(b.name),
    },
    {
      title: 'Beskrivelse',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (value: string) => value || <Text type="secondary">-</Text>,
    },
    {
      title: 'EAN',
      dataIndex: 'ean',
      key: 'ean',
      width: 140,
      render: (value: string) => value ? <Text code>{value}</Text> : <Text type="secondary">-</Text>,
    },
    {
      title: 'Producent',
      dataIndex: 'manufacturer',
      key: 'manufacturer',
      width: 150,
      sorter: (a, b) => (a.manufacturer || '').localeCompare(b.manufacturer || ''),
      render: (value: string) => value || <Text type="secondary">-</Text>,
    },
    {
      title: 'Pris',
      dataIndex: 'unitPrice',
      key: 'unitPrice',
      width: 120,
      align: 'right',
      sorter: (a, b) => a.unitPrice - b.unitPrice,
      render: (value: number) => formatCurrency(value),
    },
    {
      title: 'Enhed',
      dataIndex: 'unit',
      key: 'unit',
      width: 80,
      render: (value: string) => value || <Text type="secondary">-</Text>,
    },
    {
      title: 'Moms',
      dataIndex: 'vatCode',
      key: 'vatCode',
      width: 80,
      render: (value: string) => <Tag>{value}</Tag>,
    },
    {
      title: 'Status',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      render: (isActive: boolean) => (
        <StatusBadge
          status={isActive ? 'success' : 'error'}
          text={isActive ? 'Aktiv' : 'Inaktiv'}
        />
      ),
    },
    {
      title: '',
      key: 'actions',
      width: 120,
      render: (_: unknown, record: Product) => (
        <Space size="small">
          <Button type="text" icon={<EyeOutlined />} onClick={() => handleView(record)} />
          <Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
          <Popconfirm
            title={record.isActive ? 'Deaktiver produkt?' : 'Genaktiver produkt?'}
            onConfirm={() => handleToggleActive(record)}
            okText="Ja"
            cancelText="Nej"
          >
            <Button
              type="text"
              danger={record.isActive}
              icon={record.isActive ? <StopOutlined /> : <CheckOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  if (loading) {
    return (
      <div>
        <PageHeader
          title="Produkter"
          subtitle={company?.name}
          breadcrumbs={[{ title: 'Fakturering', path: '/fakturaer' }, { title: 'Produkter' }]}
        />
        <Row gutter={spacing.md} style={{ marginBottom: spacing.lg }}>
          <Col xs={24} sm={8}><Card><Skeleton active paragraph={{ rows: 2 }} /></Card></Col>
          <Col xs={24} sm={8}><Card><Skeleton active paragraph={{ rows: 2 }} /></Card></Col>
          <Col xs={24} sm={8}><Card><Skeleton active paragraph={{ rows: 2 }} /></Card></Col>
        </Row>
        <Card><Skeleton active paragraph={{ rows: 8 }} /></Card>
      </div>
    );
  }

  if (error) {
    return (
      <div>
        <PageHeader
          title="Produkter"
          subtitle={company?.name}
          breadcrumbs={[{ title: 'Fakturering', path: '/fakturaer' }, { title: 'Produkter' }]}
        />
        <Alert
          message="Fejl ved indlæsning af produkter"
          description={error.message}
          type="error"
          showIcon
          action={
            <Button size="small" onClick={() => window.location.reload()}>
              Prøv igen
            </Button>
          }
        />
      </div>
    );
  }

  return (
    <div>
      <PageHeader
        title="Produkter"
        subtitle={company?.name}
        breadcrumbs={[{ title: 'Fakturering', path: '/fakturaer' }, { title: 'Produkter' }]}
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            Opret produkt
          </Button>
        }
      />

      {/* Statistics */}
      <Row gutter={spacing.md} style={{ marginBottom: spacing.lg }}>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic title="Totalt antal" value={stats.total} prefix={<ShoppingOutlined />} />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic title="Aktive produkter" value={stats.active} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col xs={24} sm={8}>
          <Card>
            <Statistic
              title="Gns. pris (aktive)"
              value={stats.active > 0 ? stats.totalValue / stats.active : 0}
              precision={2}
              suffix="DKK"
            />
          </Card>
        </Col>
      </Row>

      {/* Search and filters */}
      <Card style={{ marginBottom: spacing.md }}>
        <Space wrap>
          <Input
            placeholder="Søg efter navn, produktnummer..."
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            allowClear
            style={{ width: 300 }}
          />
          <Space>
            <Text type="secondary" style={{ fontSize: 13 }}>Vis inaktive</Text>
            <Switch size="small" checked={showInactive} onChange={setShowInactive} />
          </Space>
        </Space>
      </Card>

      {/* Products table */}
      {filteredProducts.length === 0 && searchText === '' && !showInactive ? (
        <EmptyState
          icon={<ShoppingOutlined style={{ fontSize: 48 }} />}
          title="Ingen produkter endnu"
          description="Opret dit første produkt for at komme i gang med hurtig fakturering"
          primaryAction={{
            label: 'Opret produkt',
            onClick: handleCreate,
            icon: <PlusOutlined />,
          }}
        />
      ) : (
        <Card>
          <Table
            columns={columns}
            dataSource={filteredProducts}
            rowKey="id"
            pagination={{
              pageSize: 20,
              showSizeChanger: true,
              showTotal: (total) => `${total} produkter`,
            }}
          />
        </Card>
      )}

      {/* Create/Edit Modal */}
      <Modal
        title={editingProduct ? 'Rediger produkt' : 'Opret produkt'}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
          setEditingProduct(null);
          form.resetFields();
        }}
        onOk={handleSubmit}
        okText={editingProduct ? 'Gem' : 'Opret'}
        cancelText="Annuller"
        confirmLoading={createProductMutation.isPending || updateProductMutation.isPending}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="productNumber" label="Produktnummer">
                <Input placeholder="F.eks. P001 (valgfrit)" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label="Navn"
                rules={[{ required: true, message: 'Indtast produktnavn' }]}
              >
                <Input placeholder="Produktnavn" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name="description" label="Beskrivelse">
            <Input.TextArea rows={2} placeholder="Beskrivelse (kopieres til fakturalinje)" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="ean" label="EAN/Stregkode">
                <Input placeholder="EAN-13 eller anden stregkode" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="manufacturer" label="Producent">
                <AutoComplete
                  allowClear
                  placeholder="Indtast eller vælg producent"
                  onSearch={setManufacturerSearch}
                  options={manufacturers.map(m => ({ value: m, label: m }))}
                  filterOption={(inputValue, option) =>
                    option?.value.toLowerCase().includes(inputValue.toLowerCase()) ?? false
                  }
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="unitPrice"
                label="Enhedspris (ekskl. moms)"
                rules={[{ required: true, message: 'Indtast pris' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  min={0}
                  step={0.01}
                  precision={2}
                  addonAfter="DKK"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="vatCode"
                label="Momskode"
                rules={[{ required: true, message: 'Vælg momskode' }]}
              >
                <Select options={vatCodeOptions} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="unit" label="Enhed">
                <Select options={unitOptions} allowClear placeholder="Vælg enhed" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      {/* View Drawer */}
      <Drawer
        title="Produktdetaljer"
        open={isDrawerOpen}
        onClose={() => {
          setIsDrawerOpen(false);
          setSelectedProduct(null);
        }}
        width={500}
      >
        {selectedProduct && (
          <div>
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="Produktnummer">
                {selectedProduct.productNumber || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="Navn">{selectedProduct.name}</Descriptions.Item>
              <Descriptions.Item label="Beskrivelse">
                {selectedProduct.description || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="Enhedspris">
                {formatCurrency(selectedProduct.unitPrice)}
              </Descriptions.Item>
              <Descriptions.Item label="Enhed">{selectedProduct.unit || '-'}</Descriptions.Item>
              <Descriptions.Item label="Momskode">
                <Tag>{selectedProduct.vatCode}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="EAN">
                {selectedProduct.ean || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="Producent">
                {selectedProduct.manufacturer || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="Status">
                <StatusBadge
                  status={selectedProduct.isActive ? 'success' : 'error'}
                  text={selectedProduct.isActive ? 'Aktiv' : 'Inaktiv'}
                />
              </Descriptions.Item>
              <Descriptions.Item label="Oprettet">
                {formatDate(selectedProduct.createdAt)}
              </Descriptions.Item>
              <Descriptions.Item label="Opdateret">
                {formatDate(selectedProduct.updatedAt)}
              </Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: spacing.lg }}>
              <Space>
                <Button icon={<EditOutlined />} onClick={() => handleEdit(selectedProduct)}>
                  Rediger
                </Button>
                <Popconfirm
                  title={
                    selectedProduct.isActive ? 'Deaktiver dette produkt?' : 'Genaktiver dette produkt?'
                  }
                  onConfirm={() => handleToggleActive(selectedProduct)}
                  okText="Ja"
                  cancelText="Nej"
                >
                  <Button danger={selectedProduct.isActive}>
                    {selectedProduct.isActive ? 'Deaktiver' : 'Genaktiver'}
                  </Button>
                </Popconfirm>
              </Space>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
}
