import * as vscode from 'vscode';
import { singletonPanel } from './shared';

const PROJECT_KEY = 'hplToolbox.dailyUpdate.lastProject';
const store: { panel: vscode.WebviewPanel | null } = { panel: null };

export function openDailyUpdate(context: vscode.ExtensionContext) {
  const { panel, isNew } = singletonPanel(store, 'hplToolbox.dailyUpdate', 'Daily Update');
  if (!isNew) return;

  const lastProject = context.globalState.get<string>(PROJECT_KEY, '');
  panel.webview.html = getHtml(lastProject);

  panel.webview.onDidReceiveMessage(async (msg) => {
    if (msg.type === 'submit') {
      const text = formatMessage(msg.payload);
      await vscode.env.clipboard.writeText(text);
      await context.globalState.update(PROJECT_KEY, msg.payload.project);
      vscode.window.showInformationMessage('Daily update copied to clipboard.');
      panel.dispose();
    }
  });
}

function formatMessage(p: { date: string; status: string; project: string; remarks: string }): string {
  const bullets = p.remarks
    .split(/\r?\n/)
    .map((l) => l.replace(/^\s*[-*]\s*/, '').trim())
    .filter((l) => l.length > 0)
    .map((l) => `- ${l}`)
    .join('\n');

  const lines = [
    `Date: ${formatDate(p.date)}`,
    `Status: ${p.status}`,
    `Project: ${p.project}`,
    `Remarks:`,
    bullets,
  ];

  if (p.status === 'For OT') {
    lines.push('@Joyce Lanot , @Reland Pigte, @Anthony Castor, @Angela Grace');
  }

  return lines.join('\n');
}

function formatDate(iso: string): string {
  const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
  if (!m) return iso;
  return `${m[2]}/${m[3]}/${m[1]}`;
}

function escapeAttr(s: string): string {
  return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function getHtml(lastProject: string): string {
  const today = new Date().toISOString().slice(0, 10);
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline';" />
<style>
  body { font-family: var(--vscode-font-family); color: var(--vscode-foreground); padding: 16px; max-width: 520px; }
  label { display: block; margin-top: 12px; font-size: 12px; opacity: 0.85; }
  input, select, textarea {
    width: 100%; box-sizing: border-box; margin-top: 4px; padding: 6px 8px;
    background: var(--vscode-input-background); color: var(--vscode-input-foreground);
    border: 1px solid var(--vscode-input-border, transparent); font-family: inherit; font-size: 13px;
  }
  textarea { min-height: 96px; resize: vertical; }
  button {
    margin-top: 16px; padding: 8px 16px; cursor: pointer;
    background: var(--vscode-button-background); color: var(--vscode-button-foreground);
    border: none; font-size: 13px;
  }
  button:hover { background: var(--vscode-button-hoverBackground); }
</style>
</head>
<body>
  <h2 style="margin:0 0 4px 0;">Daily Update</h2>
  <div style="font-size:12px;opacity:0.7;">Submit copies the formatted text to your clipboard.</div>

  <label for="date">Date</label>
  <input type="date" id="date" value="${today}" />

  <label for="status">Status</label>
  <select id="status">
    <option>Started</option>
    <option>Progress</option>
    <option>Finished</option>
    <option>Client Feedback</option>
    <option>For OT</option>
  </select>

  <label for="project">Project</label>
  <input type="text" id="project" placeholder="Project name" value="${escapeAttr(lastProject)}" />

  <label for="remarks">Remarks</label>
  <textarea id="remarks" placeholder="What did you do?"></textarea>

  <button id="submit">Submit</button>

<script>
  const vscode = acquireVsCodeApi();
  document.getElementById('submit').addEventListener('click', () => {
    vscode.postMessage({
      type: 'submit',
      payload: {
        date: document.getElementById('date').value,
        status: document.getElementById('status').value,
        project: document.getElementById('project').value.trim(),
        remarks: document.getElementById('remarks').value.trim(),
      },
    });
  });
</script>
</body>
</html>`;
}
