import { useState } from 'react';
import {
  Typography,
  Card,
  Row,
  Col,
  Form,
  Input,
  Button,
  Tabs,
  Switch,
  Divider,
  Avatar,
  Upload,
  Select,
  Modal,
} from 'antd';
import { showSuccess, showError, showInfo, showValidationError } from '@/lib/errorHandling';
import {
  SaveOutlined,
  UserOutlined,
  LockOutlined,
  BellOutlined,
  GlobalOutlined,
  UploadOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { spacing } from '@/styles/designTokens';

const { Title, Text } = Typography;

// Mock user data - replace with actual auth context
const mockUser = {
  id: '1',
  name: 'Nicolaj Hartmann',
  email: 'nicolaj@example.com',
  avatar: null,
  phone: '+45 12 34 56 78',
  language: 'da',
  timezone: 'Europe/Copenhagen',
  notifications: {
    email: true,
    browser: true,
    weeklyReport: true,
    deadlineReminders: true,
  },
};

export default function UserSettings() {
  const [profileForm] = Form.useForm();
  const [passwordForm] = Form.useForm();
  const [notificationForm] = Form.useForm();
  const [isChangingPassword, setIsChangingPassword] = useState(false);

  const handleSaveProfile = async () => {
    try {
      const values = await profileForm.validateFields();
      console.log('Saving profile:', values);
      showSuccess('Profil opdateret');
    } catch (error) {
      console.error('Validation failed:', error);
      showValidationError();
    }
  };

  const handleChangePassword = async () => {
    try {
      const values = await passwordForm.validateFields();
      if (values.newPassword !== values.confirmPassword) {
        showError('Adgangskoderne stemmer ikke overens');
        return;
      }
      console.log('Changing password');
      showSuccess('Adgangskode opdateret');
      passwordForm.resetFields();
      setIsChangingPassword(false);
    } catch (error) {
      console.error('Validation failed:', error);
      showValidationError();
    }
  };

  const handleSaveNotifications = async () => {
    try {
      const values = await notificationForm.validateFields();
      console.log('Saving notifications:', values);
      showSuccess('Notifikationsindstillinger gemt');
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleDeleteAccount = () => {
    Modal.confirm({
      title: 'Slet konto',
      icon: <ExclamationCircleOutlined />,
      content: (
        <div>
          <p>Er du sikker på, at du vil slette din konto?</p>
          <p><Text type="danger">Denne handling kan ikke fortrydes.</Text></p>
        </div>
      ),
      okText: 'Ja, slet min konto',
      okType: 'danger',
      cancelText: 'Annuller',
      onOk() {
        showInfo('Kontosletning er ikke implementeret endnu');
      },
    });
  };

  const uploadProps: UploadProps = {
    name: 'avatar',
    showUploadList: false,
    beforeUpload: (file) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        showError('Du kan kun uploade billedfiler');
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        showError('Billedet skal være mindre end 2MB');
      }
      return false; // Prevent auto upload
    },
    onChange: (info) => {
      console.log('Upload:', info.file);
      showSuccess('Profilbillede opdateret');
    },
  };

  const tabItems = [
    {
      key: 'profile',
      label: (
        <span>
          <UserOutlined /> Profil
        </span>
      ),
      children: (
        <Card>
          <div style={{ marginBottom: spacing.xl }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: spacing.lg }}>
              <Avatar size={80} icon={<UserOutlined />} src={mockUser.avatar} />
              <div>
                <Upload {...uploadProps}>
                  <Button icon={<UploadOutlined />}>Skift profilbillede</Button>
                </Upload>
                <Text type="secondary" style={{ display: 'block', marginTop: spacing.xs }}>
                  JPG eller PNG, max 2MB
                </Text>
              </div>
            </div>
          </div>

          <Form
            form={profileForm}
            layout="vertical"
            initialValues={{
              name: mockUser.name,
              email: mockUser.email,
              phone: mockUser.phone,
            }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="name"
                  label="Fulde navn"
                  rules={[{ required: true, message: 'Indtast dit navn' }]}
                >
                  <Input />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="email"
                  label="Email"
                  rules={[
                    { required: true, message: 'Indtast din email' },
                    { type: 'email', message: 'Indtast en gyldig email' },
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="phone" label="Telefon">
                  <Input />
                </Form.Item>
              </Col>
            </Row>

            <div style={{ textAlign: 'right' }}>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleSaveProfile}>
                Gem profil
              </Button>
            </div>
          </Form>
        </Card>
      ),
    },
    {
      key: 'security',
      label: (
        <span>
          <LockOutlined /> Sikkerhed
        </span>
      ),
      children: (
        <Card>
          <Title level={5}>Skift adgangskode</Title>
          <Text type="secondary" style={{ display: 'block', marginBottom: spacing.lg }}>
            Vi anbefaler at bruge en stærk adgangskode, som du ikke bruger andre steder.
          </Text>

          {!isChangingPassword ? (
            <Button onClick={() => setIsChangingPassword(true)}>
              Skift adgangskode
            </Button>
          ) : (
            <Form form={passwordForm} layout="vertical" style={{ maxWidth: 400 }}>
              <Form.Item
                name="currentPassword"
                label="Nuværende adgangskode"
                rules={[{ required: true, message: 'Indtast din nuværende adgangskode' }]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                name="newPassword"
                label="Ny adgangskode"
                rules={[
                  { required: true, message: 'Indtast en ny adgangskode' },
                  { min: 8, message: 'Adgangskoden skal være mindst 8 tegn' },
                ]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item
                name="confirmPassword"
                label="Bekræft ny adgangskode"
                rules={[{ required: true, message: 'Bekræft din nye adgangskode' }]}
              >
                <Input.Password />
              </Form.Item>

              <div style={{ display: 'flex', gap: spacing.sm }}>
                <Button type="primary" onClick={handleChangePassword}>
                  Gem ny adgangskode
                </Button>
                <Button onClick={() => setIsChangingPassword(false)}>
                  Annuller
                </Button>
              </div>
            </Form>
          )}

          <Divider />

          <Title level={5}>To-faktor-godkendelse</Title>
          <Text type="secondary" style={{ display: 'block', marginBottom: spacing.md }}>
            Tilføj et ekstra lag af sikkerhed til din konto.
          </Text>
          <Button disabled>Aktiver 2FA (kommer snart)</Button>

          <Divider />

          <Title level={5} style={{ color: '#ff4d4f' }}>Farezone</Title>
          <Text type="secondary" style={{ display: 'block', marginBottom: spacing.md }}>
            Når du sletter din konto, mister du al adgang til virksomheder og data.
          </Text>
          <Button danger onClick={handleDeleteAccount}>
            Slet min konto
          </Button>
        </Card>
      ),
    },
    {
      key: 'notifications',
      label: (
        <span>
          <BellOutlined /> Notifikationer
        </span>
      ),
      children: (
        <Card>
          <Form
            form={notificationForm}
            layout="vertical"
            initialValues={mockUser.notifications}
          >
            <Title level={5}>Email-notifikationer</Title>

            <Form.Item
              name="email"
              valuePropName="checked"
              style={{ marginBottom: spacing.sm }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <Text strong>Generelle emails</Text>
                  <Text type="secondary" style={{ display: 'block' }}>
                    Modtag vigtige opdateringer om din konto
                  </Text>
                </div>
                <Switch defaultChecked={mockUser.notifications.email} />
              </div>
            </Form.Item>

            <Form.Item
              name="weeklyReport"
              valuePropName="checked"
              style={{ marginBottom: spacing.sm }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <Text strong>Ugentlig rapport</Text>
                  <Text type="secondary" style={{ display: 'block' }}>
                    Få en opsummering af ugens bogføring hver mandag
                  </Text>
                </div>
                <Switch defaultChecked={mockUser.notifications.weeklyReport} />
              </div>
            </Form.Item>

            <Form.Item
              name="deadlineReminders"
              valuePropName="checked"
              style={{ marginBottom: spacing.sm }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <Text strong>Påmindelser om frister</Text>
                  <Text type="secondary" style={{ display: 'block' }}>
                    Få besked når momsfrister eller andre deadlines nærmer sig
                  </Text>
                </div>
                <Switch defaultChecked={mockUser.notifications.deadlineReminders} />
              </div>
            </Form.Item>

            <Divider />

            <Title level={5}>Browser-notifikationer</Title>

            <Form.Item
              name="browser"
              valuePropName="checked"
              style={{ marginBottom: spacing.sm }}
            >
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <Text strong>Push-notifikationer</Text>
                  <Text type="secondary" style={{ display: 'block' }}>
                    Modtag notifikationer direkte i browseren
                  </Text>
                </div>
                <Switch defaultChecked={mockUser.notifications.browser} />
              </div>
            </Form.Item>

            <div style={{ textAlign: 'right', marginTop: spacing.lg }}>
              <Button type="primary" icon={<SaveOutlined />} onClick={handleSaveNotifications}>
                Gem notifikationsindstillinger
              </Button>
            </div>
          </Form>
        </Card>
      ),
    },
    {
      key: 'preferences',
      label: (
        <span>
          <GlobalOutlined /> Præferencer
        </span>
      ),
      children: (
        <Card>
          <Form
            layout="vertical"
            initialValues={{
              language: mockUser.language,
              timezone: mockUser.timezone,
            }}
          >
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="language" label="Sprog">
                  <Select
                    options={[
                      { value: 'da', label: 'Dansk' },
                      { value: 'en', label: 'English' },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="timezone" label="Tidszone">
                  <Select
                    options={[
                      { value: 'Europe/Copenhagen', label: 'København (GMT+1)' },
                      { value: 'Europe/London', label: 'London (GMT)' },
                      { value: 'America/New_York', label: 'New York (GMT-5)' },
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>

            <Divider />

            <Title level={5}>Visningsindstillinger</Title>

            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name="dateFormat" label="Datoformat">
                  <Select
                    defaultValue="dd-mm-yyyy"
                    options={[
                      { value: 'dd-mm-yyyy', label: 'DD-MM-YYYY (31-12-2025)' },
                      { value: 'mm-dd-yyyy', label: 'MM-DD-YYYY (12-31-2025)' },
                      { value: 'yyyy-mm-dd', label: 'YYYY-MM-DD (2025-12-31)' },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item name="numberFormat" label="Talformat">
                  <Select
                    defaultValue="danish"
                    options={[
                      { value: 'danish', label: '1.234,56 (dansk)' },
                      { value: 'english', label: '1,234.56 (engelsk)' },
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>

            <div style={{ textAlign: 'right' }}>
              <Button type="primary" icon={<SaveOutlined />}>
                Gem præferencer
              </Button>
            </div>
          </Form>
        </Card>
      ),
    },
  ];

  return (
    <div>
      {/* Header */}
      <div style={{ marginBottom: spacing.lg }}>
        <Title level={4} style={{ margin: 0 }}>
          Min profil
        </Title>
        <Text type="secondary">Administrer dine personlige indstillinger</Text>
      </div>

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