import { useState, useEffect, type ReactElement, type FormEvent } from 'react';
import styled from '@lilith/ui-styled-components';
import { getSettings, putSettings, type MacSyncSettings } from '@/api/settings';

// ---------------------------------------------------------------------------
// Styles
// ---------------------------------------------------------------------------

const Root = styled.div`
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow-y: auto;
`;

const PageHeading = styled.h1`
  margin: 0;
  padding: 14px 20px;
  font-size: 18px;
  font-weight: 700;
  color: #e0e0f0;
  border-bottom: 1px solid #2a2a38;
  background: #0a0a0f;
`;

const Section = styled.section`
  padding: 24px 24px 0;
`;

const SectionTitle = styled.h2`
  margin: 0 0 12px;
  font-size: 13px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.08em;
  color: #8a8a9a;
`;

const Card = styled.div`
  background: #13131a;
  border: 1px solid #2a2a38;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 24px;
`;

const FieldRow = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  padding: 12px 16px;
  border-bottom: 1px solid #1e1e2a;

  &:last-child {
    border-bottom: none;
  }
`;

const FieldLabel = styled.label`
  font-size: 12px;
  color: #8a8a9a;
`;

const FieldInput = styled.input`
  width: 100%;
  background: #0d0d14;
  border: 1px solid #2a2a38;
  border-radius: 4px;
  padding: 6px 10px;
  font-size: 13px;
  color: #d0d0e0;
  outline: none;
  box-sizing: border-box;

  &:focus {
    border-color: rgba(201, 168, 76, 0.5);
  }

  &:disabled {
    opacity: 0.4;
    cursor: not-allowed;
  }
`;

const Row = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #1e1e2a;
  gap: 16px;

  &:last-child {
    border-bottom: none;
  }
`;

const RowLabel = styled.span`
  font-size: 13px;
  color: #d0d0e0;
`;

const RowValue = styled.span`
  font-size: 12px;
  color: #8a8a9a;
  text-align: right;
`;

const SaveBar = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 24px 24px;
`;

const SaveBtn = styled.button<{ $saving?: boolean }>`
  background: ${(p) => (p.$saving ? '#3a3a2a' : 'rgba(201,168,76,0.15)')};
  color: ${(p) => (p.$saving ? '#8a8a4a' : 'rgba(201,168,76,0.9)')};
  border: 1px solid rgba(201, 168, 76, 0.3);
  border-radius: 6px;
  padding: 7px 18px;
  font-size: 13px;
  font-weight: 600;
  cursor: ${(p) => (p.$saving ? 'not-allowed' : 'pointer')};
  transition: background 0.15s;

  &:hover:not(:disabled) {
    background: rgba(201, 168, 76, 0.25);
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;

const StatusMsg = styled.span<{ $error?: boolean }>`
  font-size: 12px;
  color: ${(p) => (p.$error ? '#e05a5a' : '#5ae05a')};
`;

const Notice = styled.p`
  font-size: 12px;
  color: #8a8a9a;
  margin: 0;
  padding: 16px 24px;
  line-height: 1.6;
`;

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

export function SettingsTab(): ReactElement {
  const isLocal =
    typeof window !== 'undefined' && window.location.port === '8765';

  const [settings, setSettings] = useState<MacSyncSettings | null>(null);
  const [draft, setDraft] = useState<Partial<MacSyncSettings>>({});
  const [saving, setSaving] = useState(false);
  const [status, setStatus] = useState<{ msg: string; error: boolean } | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);

  useEffect(() => {
    if (!isLocal) return;
    getSettings()
      .then((s) => {
        setSettings(s);
        setDraft({
          serverURL: s.serverURL,
          webServerPort: s.webServerPort,
          serviceToken: s.serviceToken ?? '',
          deviceName: s.deviceName ?? '',
        });
      })
      .catch(() => setLoadError('Could not load settings from Mac agent.'));
  }, [isLocal]);

  async function handleSave(e: FormEvent): Promise<void> {
    e.preventDefault();
    setSaving(true);
    setStatus(null);
    try {
      const updates: Partial<MacSyncSettings> = {};
      if (draft.serverURL !== undefined) updates.serverURL = draft.serverURL.trim();
      if (draft.webServerPort !== undefined) updates.webServerPort = Number(draft.webServerPort);
      if (draft.serviceToken !== undefined) updates.serviceToken = draft.serviceToken.trim();
      const trimmedName = draft.deviceName?.trim();
      if (trimmedName) updates.deviceName = trimmedName;
      const saved = await putSettings(updates);
      setSettings(saved);
      setDraft({
        serverURL: saved.serverURL,
        webServerPort: saved.webServerPort,
        serviceToken: saved.serviceToken ?? '',
        deviceName: saved.deviceName ?? '',
      });
      setStatus({ msg: 'Saved. Reload dashboard to apply API authentication changes.', error: false });
    } catch {
      setStatus({ msg: 'Save failed — check that the Mac agent is running.', error: true });
    } finally {
      setSaving(false);
    }
  }

  if (!isLocal) {
    return (
      <Root>
        <PageHeading>Settings</PageHeading>
        <Notice>
          Mac agent settings are only available when this dashboard is served directly by the
          MacSync agent at{' '}
          <a href="http://localhost:8765" style={{ color: 'rgba(201,168,76,0.8)' }}>
            http://localhost:8765
          </a>
          . Open that URL on your Mac to edit the server URL, device name, and other options.
        </Notice>

        <Section>
          <SectionTitle>About</SectionTitle>
          <Card>
            <Row>
              <RowLabel>Dashboard version</RowLabel>
              <RowValue>0.1.0</RowValue>
            </Row>
            <Row>
              <RowLabel>API surface</RowLabel>
              <RowValue>/my/messages, /my/photos, /my/mail</RowValue>
            </Row>
          </Card>
        </Section>
      </Root>
    );
  }

  return (
    <Root>
      <PageHeading>Settings</PageHeading>

      {loadError && <Notice style={{ color: '#e05a5a' }}>{loadError}</Notice>}

      <form onSubmit={handleSave}>
        <Section>
          <SectionTitle>Server</SectionTitle>
          <Card>
            <FieldRow>
              <FieldLabel htmlFor="serverURL">Server URL</FieldLabel>
              <FieldInput
                id="serverURL"
                type="url"
                value={draft.serverURL ?? ''}
                onChange={(e) => setDraft((d) => ({ ...d, serverURL: e.target.value }))}
                placeholder="http://10.0.0.11:3201"
                disabled={saving || !settings}
              />
            </FieldRow>
            <FieldRow>
              <FieldLabel htmlFor="webServerPort">Dashboard port</FieldLabel>
              <FieldInput
                id="webServerPort"
                type="number"
                min={1024}
                max={65535}
                value={draft.webServerPort ?? 8765}
                onChange={(e) =>
                  setDraft((d) => ({ ...d, webServerPort: Number(e.target.value) }))
                }
                disabled={saving || !settings}
              />
            </FieldRow>
            <FieldRow>
              <FieldLabel htmlFor="serviceToken">Service Token</FieldLabel>
              <FieldInput
                id="serviceToken"
                type="password"
                value={draft.serviceToken ?? ''}
                onChange={(e) => setDraft((d) => ({ ...d, serviceToken: e.target.value }))}
                placeholder="64-character hex token for API authentication"
                disabled={saving || !settings}
              />
            </FieldRow>
          </Card>
        </Section>

        <Section>
          <SectionTitle>Device</SectionTitle>
          <Card>
            <FieldRow>
              <FieldLabel htmlFor="deviceName">Device name</FieldLabel>
              <FieldInput
                id="deviceName"
                type="text"
                value={draft.deviceName ?? ''}
                onChange={(e) => setDraft((d) => ({ ...d, deviceName: e.target.value }))}
                placeholder="plum"
                disabled={saving || !settings}
              />
            </FieldRow>
            {settings?.imessageOwnAddresses?.length ? (
              <Row>
                <RowLabel>iMessage addresses</RowLabel>
                <RowValue>{settings.imessageOwnAddresses.join(', ')}</RowValue>
              </Row>
            ) : null}
            {settings?.imailOwnAddresses?.length ? (
              <Row>
                <RowLabel>iMail addresses</RowLabel>
                <RowValue>{settings.imailOwnAddresses.join(', ')}</RowValue>
              </Row>
            ) : null}
          </Card>
        </Section>

        <SaveBar>
          <SaveBtn type="submit" $saving={saving} disabled={saving || !settings}>
            {saving ? 'Saving…' : 'Save'}
          </SaveBtn>
          {status && <StatusMsg $error={status.error}>{status.msg}</StatusMsg>}
        </SaveBar>
      </form>

      <Section>
        <SectionTitle>Config file</SectionTitle>
        <Card>
          <Row>
            <RowLabel>Path</RowLabel>
            <RowValue style={{ fontFamily: 'monospace', fontSize: 11 }}>
              ~/.config/com.lilith.mac-sync/config.json
            </RowValue>
          </Row>
        </Card>
      </Section>

      <Section>
        <SectionTitle>About</SectionTitle>
        <Card>
          <Row>
            <RowLabel>Dashboard version</RowLabel>
            <RowValue>0.1.0</RowValue>
          </Row>
          <Row>
            <RowLabel>API surface</RowLabel>
            <RowValue>/my/messages, /my/photos, /my/mail</RowValue>
          </Row>
        </Card>
      </Section>
    </Root>
  );
}
