import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Typography,
  Button,
  Card,
  Table,
  Space,
  Tag,
  Modal,
  Form,
  Input,
  Select,
  Switch,
  Spin,
  Alert,
  Drawer,
  Descriptions,
  Popconfirm,
  Row,
  Col,
  Statistic,
} from 'antd';
import { showSuccess, showError } from '@/lib/errorHandling';
import {
  PlusOutlined,
  EditOutlined,
  SearchOutlined,
  UserOutlined,
  ShopOutlined,
  EyeOutlined,
  StopOutlined,
  CheckOutlined,
  FileTextOutlined,
} from '@ant-design/icons';
import { useCompany } from '@/hooks/useCompany';
import { usePageHotkeys } from '@/hooks/usePageHotkeys';
import { ShortcutTooltip } from '@/components/shared/ShortcutTooltip';
import { useCustomers, type Customer } from '@/api/queries/customerQueries';
import {
  useCreateCustomer,
  useUpdateCustomer,
  useDeactivateCustomer,
  useReactivateCustomer,
  type CreateCustomerInput,
  type UpdateCustomerInput,
} from '@/api/mutations/customerMutations';
import { formatDate, validateCVRModulus11 } 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 { Title, Text } = Typography;

export default function Kunder() {
  const navigate = useNavigate();
  const { company } = useCompany();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDrawerOpen, setIsDrawerOpen] = useState(false);
  const [editingCustomer, setEditingCustomer] = useState<Customer | null>(null);
  const [selectedCustomer, setSelectedCustomer] = useState<Customer | null>(null);
  const [searchText, setSearchText] = useState('');
  const [showInactive, setShowInactive] = useState(false);
  const [form] = Form.useForm();

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

  // Mutations using new hooks
  const createCustomerMutation = useCreateCustomer();
  const updateCustomerMutation = useUpdateCustomer();
  const deactivateCustomerMutation = useDeactivateCustomer();
  const reactivateCustomerMutation = useReactivateCustomer();

  // Filter customers
  const filteredCustomers = useMemo(() => {
    return customers.filter((customer) => {
      const matchesSearch =
        searchText === '' ||
        customer.name.toLowerCase().includes(searchText.toLowerCase()) ||
        customer.customerNumber.includes(searchText) ||
        (customer.cvr && customer.cvr.includes(searchText)) ||
        (customer.email && customer.email.toLowerCase().includes(searchText.toLowerCase()));

      const matchesStatus = showInactive || customer.isActive;

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

  // Statistics
  const stats = useMemo(() => {
    const active = customers.filter((c) => c.isActive).length;
    const business = customers.filter((c) => c.customerType === 'Business').length;
    const private_ = customers.filter((c) => c.customerType === 'Private').length;
    return { total: customers.length, active, business, private: private_ };
  }, [customers]);

  const handleCreate = () => {
    setEditingCustomer(null);
    form.resetFields();
    form.setFieldsValue({ customerType: 'Business', paymentTermsDays: 30 });
    setIsModalOpen(true);
  };

  const handleEdit = (customer: Customer) => {
    setEditingCustomer(customer);
    form.setFieldsValue({
      customerType: customer.customerType,
      name: customer.name,
      cvr: customer.cvr,
      address: customer.address,
      postalCode: customer.postalCode,
      city: customer.city,
      country: customer.country ?? 'DK',
      email: customer.email,
      phone: customer.phone,
      paymentTermsDays: customer.paymentTermsDays,
    });
    setIsModalOpen(true);
  };

  const handleView = (customer: Customer) => {
    setSelectedCustomer(customer);
    setIsDrawerOpen(true);
  };

  // Create invoice for selected customer
  const handleCreateInvoice = () => {
    if (selectedCustomer && selectedCustomer.isActive) {
      setIsDrawerOpen(false);
      navigate(`/fakturaer?create=true&customerId=${selectedCustomer.id}`);
    }
  };

  // Keyboard shortcuts for this page
  usePageHotkeys([
    {
      shortcutId: 'newCustomer',
      action: handleCreate,
    },
    {
      shortcutId: 'newInvoice',
      action: handleCreateInvoice,
      enabled: !!selectedCustomer && selectedCustomer.isActive,
    },
  ]);

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

      if (editingCustomer) {
        const input: UpdateCustomerInput = {
          id: editingCustomer.id,
          name: values.name,
          cvr: values.cvr || undefined,
          address: values.address || undefined,
          postalCode: values.postalCode || undefined,
          city: values.city || undefined,
          country: values.country || undefined,
          email: values.email || undefined,
          phone: values.phone || undefined,
          paymentTermsDays: values.paymentTermsDays,
        };
        await updateCustomerMutation.mutateAsync(input);
        showSuccess('Kunde opdateret');
      } else {
        const input: CreateCustomerInput = {
          companyId: company!.id,
          customerType: values.customerType.toUpperCase() as 'BUSINESS' | 'PRIVATE',
          name: values.name,
          cvr: values.cvr || undefined,
          address: values.address || undefined,
          postalCode: values.postalCode || undefined,
          city: values.city || undefined,
          country: values.country || 'DK',
          email: values.email || undefined,
          phone: values.phone || undefined,
          paymentTermsDays: values.paymentTermsDays ?? 30,
        };
        await createCustomerMutation.mutateAsync(input);
        showSuccess('Kunde oprettet');
      }
      setIsModalOpen(false);
      setEditingCustomer(null);
      form.resetFields();
    } catch (err) {
      if (err instanceof Error) {
        showError(err);
      }
    }
  };

  const handleToggleActive = async (customer: Customer) => {
    try {
      if (customer.isActive) {
        await deactivateCustomerMutation.mutateAsync(customer.id);
        showSuccess('Kunde deaktiveret');
      } else {
        await reactivateCustomerMutation.mutateAsync(customer.id);
        showSuccess('Kunde genaktiveret');
      }
    } catch (err) {
      if (err instanceof Error) {
        showError(err);
      }
    }
  };

  const columns: ColumnsType<Customer> = [
    {
      title: 'Kundenr.',
      dataIndex: 'customerNumber',
      key: 'customerNumber',
      width: 100,
      sorter: (a, b) => a.customerNumber.localeCompare(b.customerNumber),
      render: (value: string) => <Text code>{value}</Text>,
    },
    {
      title: 'Navn',
      dataIndex: 'name',
      key: 'name',
      sorter: (a, b) => a.name.localeCompare(b.name),
      render: (value: string, record: Customer) => (
        <Space>
          {record.customerType === 'Business' ? <ShopOutlined /> : <UserOutlined />}
          <Text strong>{value}</Text>
        </Space>
      ),
    },
    {
      title: 'CVR',
      dataIndex: 'cvr',
      key: 'cvr',
      width: 100,
      render: (value: string | undefined) => value || '-',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      key: 'email',
      ellipsis: true,
      render: (value: string | undefined) => value || '-',
    },
    {
      title: 'Betalingsbetingelser',
      dataIndex: 'paymentTermsDays',
      key: 'paymentTermsDays',
      width: 150,
      align: 'center',
      render: (value: number) => <Tag>{value} dage</Tag>,
    },
    {
      title: 'Status',
      dataIndex: 'isActive',
      key: 'isActive',
      width: 100,
      align: 'center',
      render: (value: boolean) => (
        <StatusBadge status={value ? 'active' : 'inactive'} />
      ),
    },
    {
      title: 'Handlinger',
      key: 'actions',
      width: 150,
      align: 'center',
      render: (_: unknown, record: Customer) => (
        <Space size="small">
          <Button
            type="text"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          />
          <Button
            type="text"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Popconfirm
            title={record.isActive ? 'Deaktiver kunde?' : 'Genaktiver kunde?'}
            description={
              record.isActive
                ? 'Kunden vil ikke kunne vælges ved oprettelse af fakturaer.'
                : 'Kunden kan igen bruges til fakturaer.'
            }
            onConfirm={() => handleToggleActive(record)}
            okText="Ja"
            cancelText="Nej"
          >
            <Button
              type="text"
              size="small"
              danger={record.isActive}
              icon={record.isActive ? <StopOutlined /> : <CheckOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <PageHeader
        title="Kunder"
        subtitle={company?.name}
        breadcrumbs={[{ title: 'Fakturering', path: '/fakturaer' }, { title: 'Kunder' }]}
        extra={
          <ShortcutTooltip shortcutId="newCustomer">
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              Ny kunde
            </Button>
          </ShortcutTooltip>
        }
      />

      {/* Error State */}
      {error && (
        <Alert
          message="Fejl ved indlæsning af kunder"
          description={error.message}
          type="error"
          showIcon
          style={{ marginBottom: spacing.lg }}
          action={
            <Button size="small" onClick={() => refetch()}>
              Prøv igen
            </Button>
          }
        />
      )}

      {/* Statistics */}
      <Row gutter={[spacing.lg, spacing.lg]} style={{ marginBottom: spacing.lg }}>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="Kunder i alt" value={stats.total} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic title="Aktive" value={stats.active} valueStyle={{ color: '#52c41a' }} />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Erhverv"
              value={stats.business}
              prefix={<ShopOutlined />}
            />
          </Card>
        </Col>
        <Col xs={12} sm={6}>
          <Card size="small">
            <Statistic
              title="Privat"
              value={stats.private}
              prefix={<UserOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* Filters */}
      <Card size="small" style={{ marginBottom: spacing.lg }}>
        <Space wrap>
          <Input
            placeholder="Søg kunde..."
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
            style={{ width: 250 }}
            allowClear
          />
          <Space>
            <Text type="secondary" style={{ fontSize: 13 }}>Vis inaktive</Text>
            <Switch size="small" checked={showInactive} onChange={setShowInactive} />
          </Space>
        </Space>
      </Card>

      {/* Customer Table */}
      <Card size="small">
        {loading ? (
          <Spin tip="Indlæser kunder..." style={{ display: 'block', textAlign: 'center', padding: spacing.xl }}>
            <div style={{ minHeight: 200 }} />
          </Spin>
        ) : filteredCustomers.length > 0 ? (
          <Table
            dataSource={filteredCustomers}
            columns={columns}
            rowKey="id"
            size="small"
            pagination={{ pageSize: 20, showSizeChanger: true }}
          />
        ) : (
          <EmptyState
            variant="customers"
            title="Ingen kunder"
            description={searchText ? 'Ingen kunder matcher din søgning' : 'Opret din første kunde for at komme i gang'}
            primaryAction={
              !searchText
                ? {
                    label: 'Opret kunde',
                    onClick: handleCreate,
                    icon: <PlusOutlined />,
                  }
                : undefined
            }
          />
        )}
      </Card>

      {/* Create/Edit Modal */}
      <Modal
        title={editingCustomer ? 'Rediger kunde' : 'Opret kunde'}
        open={isModalOpen}
        onCancel={() => {
          setIsModalOpen(false);
          setEditingCustomer(null);
          form.resetFields();
        }}
        onOk={handleSubmit}
        okText="Gem"
        cancelText="Annuller"
        confirmLoading={createCustomerMutation.isPending || updateCustomerMutation.isPending}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="customerType"
            label="Kundetype"
            rules={[{ required: true, message: 'Vælg kundetype' }]}
          >
            <Select
              disabled={!!editingCustomer}
              options={[
                { value: 'Business', label: 'Erhverv' },
                { value: 'Private', label: 'Privat' },
              ]}
            />
          </Form.Item>

          <Form.Item
            name="name"
            label="Navn"
            rules={[{ required: true, message: 'Indtast kundenavn' }]}
          >
            <Input placeholder="Firmanavn eller fulde navn" />
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prev, curr) => prev.customerType !== curr.customerType}
          >
            {({ getFieldValue }) =>
              getFieldValue('customerType') === 'Business' && (
                <Form.Item
                  name="cvr"
                  label="CVR-nummer"
                  rules={[
                    { required: true, message: 'CVR er påkrævet for erhvervskunder' },
                    { pattern: /^\d{8}$/, message: 'CVR skal være 8 cifre' },
                    {
                      validator: (_, value) => {
                        if (!value || value.length !== 8) return Promise.resolve();
                        if (!validateCVRModulus11(value)) {
                          return Promise.reject('Ugyldigt CVR-nummer (modulus 11 check fejlet)');
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                >
                  <Input placeholder="12345678" maxLength={8} />
                </Form.Item>
              )
            }
          </Form.Item>

          <Row gutter={16}>
            <Col span={24}>
              <Form.Item name="address" label="Adresse">
                <Input placeholder="Gade og husnummer" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="postalCode" label="Postnummer">
                <Input placeholder="1234" maxLength={10} />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="city" label="By">
                <Input placeholder="København" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="country" label="Land" initialValue="DK">
                <Select
                  showSearch
                  options={[
                    { value: 'DK', label: 'Danmark' },
                    { value: 'SE', label: 'Sverige' },
                    { value: 'NO', label: 'Norge' },
                    { value: 'DE', label: 'Tyskland' },
                    { value: 'GB', label: 'Storbritannien' },
                  ]}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="Email"
                rules={[{ type: 'email', message: 'Indtast gyldig email' }]}
              >
                <Input placeholder="kunde@firma.dk" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="phone" label="Telefon">
                <Input placeholder="+45 12 34 56 78" />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="paymentTermsDays"
            label="Betalingsbetingelser (dage)"
            initialValue={30}
          >
            <Select
              options={[
                { value: 0, label: 'Kontant' },
                { value: 8, label: '8 dage netto' },
                { value: 14, label: '14 dage netto' },
                { value: 30, label: '30 dage netto' },
                { value: 60, label: '60 dage netto' },
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* Customer Detail Drawer */}
      <Drawer
        title={selectedCustomer?.name}
        placement="right"
        width={500}
        open={isDrawerOpen}
        onClose={() => {
          setIsDrawerOpen(false);
          setSelectedCustomer(null);
        }}
        extra={
          selectedCustomer && (
            <Button icon={<EditOutlined />} onClick={() => {
              setIsDrawerOpen(false);
              handleEdit(selectedCustomer);
            }}>
              Rediger
            </Button>
          )
        }
      >
        {selectedCustomer && (
          <div>
            <Descriptions column={1} size="small" bordered>
              <Descriptions.Item label="Kundenummer">
                <Text code>{selectedCustomer.customerNumber}</Text>
              </Descriptions.Item>
              <Descriptions.Item label="Kundetype">
                <Tag icon={selectedCustomer.customerType === 'Business' ? <ShopOutlined /> : <UserOutlined />}>
                  {selectedCustomer.customerType === 'Business' ? 'Erhverv' : 'Privat'}
                </Tag>
              </Descriptions.Item>
              {selectedCustomer.cvr && (
                <Descriptions.Item label="CVR">{selectedCustomer.cvr}</Descriptions.Item>
              )}
              <Descriptions.Item label="Status">
                <StatusBadge status={selectedCustomer.isActive ? 'active' : 'inactive'} />
              </Descriptions.Item>
              <Descriptions.Item label="Adresse">
                {selectedCustomer.address || '-'}
                {selectedCustomer.postalCode && `, ${selectedCustomer.postalCode}`}
                {selectedCustomer.city && ` ${selectedCustomer.city}`}
              </Descriptions.Item>
              <Descriptions.Item label="Email">{selectedCustomer.email || '-'}</Descriptions.Item>
              <Descriptions.Item label="Telefon">{selectedCustomer.phone || '-'}</Descriptions.Item>
              <Descriptions.Item label="Betalingsbetingelser">
                {selectedCustomer.paymentTermsDays} dage
              </Descriptions.Item>
              <Descriptions.Item label="Oprettet">
                {formatDate(selectedCustomer.createdAt)}
              </Descriptions.Item>
            </Descriptions>

            <div style={{ marginTop: spacing.xl }}>
              <Title level={5}>Handlinger</Title>
              <Space direction="vertical" style={{ width: '100%' }}>
                <ShortcutTooltip shortcutId="newInvoice">
                  <Button
                    type="primary"
                    icon={<FileTextOutlined />}
                    block
                    disabled={!selectedCustomer.isActive}
                    onClick={handleCreateInvoice}
                  >
                    Opret fakturakladde
                  </Button>
                </ShortcutTooltip>
                <Button block onClick={() => {
                  setIsDrawerOpen(false);
                  navigate(`/fakturaer?customer=${selectedCustomer.id}`);
                }}>
                  Se fakturaer
                </Button>
                <Button block onClick={() => {
                  setIsDrawerOpen(false);
                  navigate(`/kreditnotaer?customer=${selectedCustomer.id}`);
                }}>
                  Se kreditnotaer
                </Button>
              </Space>
            </div>
          </div>
        )}
      </Drawer>
    </div>
  );
}
