import { Drawer, Form, Input, Select, Switch, Button, Typography, message, Space } from 'antd';
import { useState } from 'react';
import { CopyOutlined } from '@ant-design/icons';
import { api } from '@/lib/api';
import type { UserRole, CreateUserFromContactResponse } from '@/types/api';

interface CreateUserFromContactModalProps {
  open: boolean;
  contactId: string;
  contactEmail: string;
  contactName: string;
  onClose: () => void;
  onCreated: () => void;
}

const roleOptions: { value: UserRole; label: string }[] = [
  { value: 'USER', label: 'User' },
  { value: 'TEMP', label: 'Temp' },
  { value: 'MAP_ADMIN', label: 'Map Admin' },
  { value: 'INFLUENCE_ADMIN', label: 'Influence Admin' },
  { value: 'SUPER_ADMIN', label: 'Super Admin' },
];

function generatePassword(): string {
  const upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const lower = 'abcdefghijklmnopqrstuvwxyz';
  const digits = '0123456789';
  const all = upper + lower + digits + '!@#$%&*';
  const pick = (charset: string) => charset[Math.floor(Math.random() * charset.length)];
  // Guarantee at least one of each required class
  const parts = [pick(upper), pick(lower), pick(digits)];
  for (let i = 0; i < 13; i++) parts.push(pick(all));
  // Shuffle
  for (let i = parts.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [parts[i], parts[j]] = [parts[j], parts[i]];
  }
  return parts.join('');
}

export default function CreateUserFromContactModal({
  open, contactId, contactEmail, contactName, onClose, onCreated,
}: CreateUserFromContactModalProps) {
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);

  const handleGenerate = () => {
    const pw = generatePassword();
    form.setFieldsValue({ password: pw });
  };

  const handleSubmit = async (values: { password: string; role: UserRole; sendWelcomeEmail: boolean }) => {
    setSubmitting(true);
    try {
      const { data } = await api.post<CreateUserFromContactResponse>(
        `/people/contacts/${contactId}/create-user`,
        {
          password: values.password,
          role: values.role,
          sendWelcomeEmail: values.sendWelcomeEmail,
        },
      );
      const actionMsg = data.action === 'linked'
        ? 'Existing user account linked to contact'
        : 'User account created and linked';
      message.success(actionMsg);
      form.resetFields();
      onCreated();
    } catch (err: unknown) {
      const msg = (err as { response?: { data?: { error?: { message?: string } } } })
        ?.response?.data?.error?.message || 'Failed to create user account';
      message.error(msg);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Drawer
      title="Create User Account"
      open={open}
      onClose={() => { form.resetFields(); onClose(); }}
      width={480}
      placement="right"
      mask={false}
      rootStyle={{ position: 'absolute', top: 64, height: 'calc(100vh - 64px)' }}
      destroyOnClose
      extra={
        <Button type="primary" onClick={() => form.submit()} loading={submitting}>
          Create Account
        </Button>
      }
    >
      <div style={{ marginBottom: 16 }}>
        <Typography.Text type="secondary" style={{ fontSize: 12 }}>Contact</Typography.Text>
        <div style={{ fontWeight: 500 }}>{contactName}</div>
        <div style={{ color: 'rgba(255,255,255,0.65)', fontSize: 13 }}>{contactEmail}</div>
      </div>

      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        initialValues={{ role: 'USER', sendWelcomeEmail: false }}
      >
        <Form.Item
          name="password"
          label="Password"
          rules={[
            { required: true, message: 'Password is required' },
            { min: 12, message: 'Minimum 12 characters' },
            { pattern: /[A-Z]/, message: 'Must contain an uppercase letter' },
            { pattern: /[a-z]/, message: 'Must contain a lowercase letter' },
            { pattern: /[0-9]/, message: 'Must contain a digit' },
          ]}
        >
          <Space.Compact style={{ width: '100%' }}>
            <Input.Password style={{ flex: 1 }} placeholder="Min 12 chars, upper+lower+digit" />
            <Button icon={<CopyOutlined />} onClick={handleGenerate} title="Generate random password">
              Generate
            </Button>
          </Space.Compact>
        </Form.Item>

        <Form.Item name="role" label="Role">
          <Select options={roleOptions} />
        </Form.Item>

        <Form.Item name="sendWelcomeEmail" label="Send Welcome Email" valuePropName="checked">
          <Switch />
        </Form.Item>

        <Form.Item style={{ marginBottom: 0, display: 'none' }}>
          <Button type="primary" htmlType="submit">
            Create Account
          </Button>
        </Form.Item>
      </Form>
    </Drawer>
  );
}
