import {
  Typography,
  Card,
  Row,
  Col,
  Form,
  Input,
  Select,
  Button,
  Tabs,
  Switch,
  Divider,
  message,
  Space,
  Tag,
} from 'antd';
import {
  SaveOutlined,
  BuildOutlined,
  UserOutlined,
  BankOutlined,
  SettingOutlined,
} from '@ant-design/icons';
import { useCompany } from '@/hooks/useCompany';

const { Title, Text } = Typography;

export default function Settings() {
  const { company } = useCompany();
  const [companyForm] = Form.useForm();
  const [preferencesForm] = Form.useForm();

  const handleSaveCompany = async () => {
    try {
      const values = await companyForm.validateFields();
      console.log('Saving company:', values);
      message.success('Virksomhedsoplysninger gemt');
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleSavePreferences = async () => {
    try {
      const values = await preferencesForm.validateFields();
      console.log('Saving preferences:', values);
      message.success('Præferencer gemt');
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const tabItems = [
    {
      key: 'company',
      label: (
        <span>
          <BuildOutlined /> Virksomhed
        </span>
      ),
      children: (
        <Card>
          <Form
            form={companyForm}
            layout="vertical"
            initialValues={{
              name: company?.name,
              cvr: company?.cvr,
              address: company?.address,
              city: company?.city,
              postalCode: company?.postalCode,
              fiscalYearStart: company?.fiscalYearStart || 1,
              currency: company?.currency || 'DKK',
            }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="Virksomhedsnavn"
                  rules={[{ required: true, message: 'Indtast virksomhedsnavn' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="cvr"
                  label="CVR-nummer"
                  rules={[
                    { required: true, message: 'Indtast CVR-nummer' },
                    { pattern: /^\d{8}$/, message: 'CVR skal være 8 cifre' },
                  ]}
                >
                  <Input maxLength={8} />
                </Form.Item>
              </Col>
            </Row>

            <Divider>Adresse</Divider>

            <Row gutter={16}>
              <Col span={24}>
                <Form.Item name="address" label="Adresse">
                  <Input />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={8}>
                <Form.Item name="postalCode" label="Postnummer">
                  <Input maxLength={4} />
                </Form.Item>
              </Col>
              <Col span={16}>
                <Form.Item name="city" label="By">
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <Divider>Regnskab</Divider>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="fiscalYearStart"
                  label="Regnskabsår starter"
                  tooltip="Hvilken måned starter jeres regnskabsår?"
                >
                  <Select
                    options={[
                      { value: 1, label: 'Januar' },
                      { value: 2, label: 'Februar' },
                      { value: 3, label: 'Marts' },
                      { value: 4, label: 'April' },
                      { value: 5, label: 'Maj' },
                      { value: 6, label: 'Juni' },
                      { value: 7, label: 'Juli' },
                      { value: 8, label: 'August' },
                      { value: 9, label: 'September' },
                      { value: 10, label: 'Oktober' },
                      { value: 11, label: 'November' },
                      { value: 12, label: 'December' },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="currency" label="Valuta">
                  <Select
                    options={[
                      { value: 'DKK', label: 'DKK - Danske kroner' },
                      { value: 'EUR', label: 'EUR - Euro' },
                      { value: 'USD', label: 'USD - US Dollar' },
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>

            <div style={{ textAlign: 'right' }}>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleSaveCompany}>
                Gem ændringer
              </Button>
            </div>
          </Form>
        </Card>
      ),
    },
    {
      key: 'preferences',
      label: (
        <span>
          <SettingOutlined /> Præferencer
        </span>
      ),
      children: (
        <Card>
          <Form
            form={preferencesForm}
            layout="vertical"
            initialValues={{
              vatPeriod: 'quarterly',
              autoReconcile: true,
              emailNotifications: true,
              defaultPageSize: 20,
            }}
          >
            <Title level={5}>Moms</Title>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="vatPeriod"
                  label="Momsperiode"
                  tooltip="Hvor ofte indberetter I moms?"
                >
                  <Select
                    options={[
                      { value: 'monthly', label: 'Månedlig' },
                      { value: 'quarterly', label: 'Kvartalsvis' },
                      { value: 'half-yearly', label: 'Halvårlig' },
                      { value: 'yearly', label: 'Årlig' },
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Divider />

            <Title level={5}>Automatisering</Title>
            <Form.Item
              name="autoReconcile"
              label="Automatisk afstemningsforslag"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
            <Text type="secondary" style={{ display: 'block', marginTop: -16, marginBottom: 16 }}>
              Systemet vil automatisk foreslå matches mellem bank og bogføring
            </Text>

            <Divider />

            <Title level={5}>Notifikationer</Title>
            <Form.Item
              name="emailNotifications"
              label="Email-notifikationer"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
            <Text type="secondary" style={{ display: 'block', marginTop: -16, marginBottom: 16 }}>
              Modtag påmindelser om frister og vigtige handlinger
            </Text>

            <Divider />

            <Title level={5}>Visning</Title>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="defaultPageSize" label="Standard antal rækker i tabeller">
                  <Select
                    options={[
                      { value: 10, label: '10 rækker' },
                      { value: 20, label: '20 rækker' },
                      { value: 50, label: '50 rækker' },
                      { value: 100, label: '100 rækker' },
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>

            <div style={{ textAlign: 'right' }}>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleSavePreferences}>
                Gem præferencer
              </Button>
            </div>
          </Form>
        </Card>
      ),
    },
    {
      key: 'bankAccounts',
      label: (
        <span>
          <BankOutlined /> Bankkonti
        </span>
      ),
      children: (
        <Card>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <Title level={5} style={{ margin: 0 }}>
                Tilknyttede bankkonti
              </Title>
              <Button type="primary">Tilføj bankkonto</Button>
            </div>

            <Divider />

            {/* Mock bank accounts */}
            {[
              {
                id: '1',
                bankName: 'Danske Bank',
                accountName: 'Erhvervskonto',
                accountNumber: '1234-5678901234',
                ledgerAccount: '1000 - Bank',
                isActive: true,
              },
              {
                id: '2',
                bankName: 'Nordea',
                accountName: 'Opsparingskonto',
                accountNumber: '9876-5432109876',
                ledgerAccount: '1010 - Bank opsparing',
                isActive: true,
              },
            ].map((account) => (
              <Card key={account.id} size="small">
                <Row align="middle" justify="space-between">
                  <Col>
                    <Space direction="vertical" size={0}>
                      <Space>
                        <Text strong>{account.bankName}</Text>
                        <Tag color="blue">{account.accountName}</Tag>
                        {account.isActive && <Tag color="green">Aktiv</Tag>}
                      </Space>
                      <Text type="secondary">{account.accountNumber}</Text>
                      <Text type="secondary">
                        Bogføringskonto: {account.ledgerAccount}
                      </Text>
                    </Space>
                  </Col>
                  <Col>
                    <Space>
                      <Button size="small">Rediger</Button>
                      <Button size="small" danger>
                        Fjern
                      </Button>
                    </Space>
                  </Col>
                </Row>
              </Card>
            ))}
          </Space>
        </Card>
      ),
    },
    {
      key: 'users',
      label: (
        <span>
          <UserOutlined /> Brugere
        </span>
      ),
      children: (
        <Card>
          <Space direction="vertical" style={{ width: '100%' }}>
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
            >
              <Title level={5} style={{ margin: 0 }}>
                Brugere med adgang
              </Title>
              <Button type="primary">Inviter bruger</Button>
            </div>

            <Divider />

            {/* Mock users */}
            {[
              {
                id: '1',
                name: 'Admin Bruger',
                email: 'admin@example.com',
                role: 'Administrator',
                lastLogin: '2025-01-17',
              },
              {
                id: '2',
                name: 'Bogholder',
                email: 'bogholder@example.com',
                role: 'Bogholder',
                lastLogin: '2025-01-16',
              },
            ].map((user) => (
              <Card key={user.id} size="small">
                <Row align="middle" justify="space-between">
                  <Col>
                    <Space direction="vertical" size={0}>
                      <Text strong>{user.name}</Text>
                      <Text type="secondary">{user.email}</Text>
                    </Space>
                  </Col>
                  <Col>
                    <Space>
                      <Tag color={user.role === 'Administrator' ? 'gold' : 'blue'}>
                        {user.role}
                      </Tag>
                      <Text type="secondary">
                        Sidste login: {user.lastLogin}
                      </Text>
                      <Button size="small">Rediger</Button>
                    </Space>
                  </Col>
                </Row>
              </Card>
            ))}
          </Space>
        </Card>
      ),
    },
  ];

  return (
    <div>
      {/* Header */}
      <div style={{ marginBottom: 16 }}>
        <Title level={4} style={{ margin: 0 }}>
          Indstillinger
        </Title>
        <Text type="secondary">{company?.name}</Text>
      </div>

      <Tabs items={tabItems} />
    </div>
  );
}
