import { useState, useEffect } from 'react';
import { Button } from '@astryxdesign/core/Button';
import { Dialog, DialogHeader } from '@astryxdesign/core/Dialog';
import { Layout, LayoutContent, LayoutFooter } from '@astryxdesign/core/Layout';
import { FormLayout } from '@astryxdesign/core/FormLayout';
import { TextInput } from '@astryxdesign/core/TextInput';
import { Selector } from '@astryxdesign/core/Selector';
import { Banner } from '@astryxdesign/core/Banner';

import { createUser, updateUser } from '@/utils/apiClient';

const ROLES = ['admin', 'rep', 'manager'];
const EMPTY = { name: '', email: '', phone: '', role: 'rep', pin: '', password: '' };

const withValue = (opts, v) => (v && !opts.includes(v) ? [v, ...opts] : opts);
const selectorOptions = (opts, v) => withValue(opts, v).map((o) => ({ value: o, label: o.charAt(0).toUpperCase() + o.slice(1) }));

export default function UserFormDialog({ open, mode, initial, onClose, onSaved }) {
  const isEdit = mode === 'edit';
  const [form, setForm] = useState(EMPTY);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  const set = (k) => (val) => setForm((f) => ({ ...f, [k]: val }));

  useEffect(() => {
    if (open) {
      setForm({ ...EMPTY, ...(initial || {}) });
      setError(null);
    }
  }, [open, initial]);

  const handleSave = async () => {
    if (!form.name.trim()) { setError('Name is required.'); return; }
    if (!form.email.trim()) { setError('Email is required.'); return; }
    if (!isEdit && !form.password.trim()) { setError('Password is required.'); return; }
    setSaving(true);
    setError(null);

    const payload = {
      first_name: form.name.trim(),
      email: form.email.trim(),
      phone: form.phone,
      role: form.role,
      ...(form.password ? { password: form.password } : {}),
      ...(form.pin ? { pin: String(form.pin) } : {}),
    };

    try {
      if (isEdit) {
        await updateUser(initial.id, payload);
      } else {
        await createUser(payload);
      }
      onSaved();
    } catch (e) {
      setError(e.message || 'Failed to save user');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog isOpen={open} onOpenChange={(o) => { if (!o) onClose(); }} width={600} purpose="form">
      <Layout
        header={<DialogHeader title={isEdit ? 'Edit Team User' : 'Add Team User'} onOpenChange={(o) => { if (!o) onClose(); }} />}
        content={
          <LayoutContent>
            <FormLayout>
              {error && <Banner status="error" title={error} />}

              <FormLayout direction="horizontal">
                <TextInput label="Name" isRequired value={form.name} onChange={set('name')} />
                <TextInput label="Email" type="email" isRequired value={form.email} onChange={set('email')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <TextInput label="Phone" value={form.phone} onChange={set('phone')} />
                <Selector label="Role" options={selectorOptions(ROLES, form.role)} value={form.role} onChange={set('role')} />
              </FormLayout>
              <FormLayout direction="horizontal">
                <TextInput label="PIN" value={form.pin} onChange={set('pin')} />
                <TextInput
                  label={isEdit ? 'New Password (optional)' : 'Password'}
                  isRequired={!isEdit}
                  type="password"
                  value={form.password}
                  onChange={set('password')}
                />
              </FormLayout>
            </FormLayout>
          </LayoutContent>
        }
        footer={
          <LayoutFooter hasDivider>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '12px' }}>
              <Button label="Cancel" variant="ghost" onClick={onClose} isDisabled={saving} />
              <Button
                label={isEdit ? 'Save Changes' : 'Create User'}
                variant="primary"
                onClick={handleSave}
                isDisabled={saving}
                isLoading={saving}
              />
            </div>
          </LayoutFooter>
        }
      />
    </Dialog>
  );
}
