'use client';

import { useState } from 'react';
import AdminModal from '@/components/AdminModal';
import {
  CLEAR_JIRA_INCIDENT_IMPORT_CONFIRM,
  clearIncidentJiraImportedData,
  jiraTcocBackfillWorkspaceLinks,
  jiraTicketsImportOnce,
} from '@/lib/admin-incidents';

const IMPORT_PROJECT_OPTIONS = ['TCOC', 'O11Y', 'TCID', 'ST'] as const;

export default function AdminMaintenancePanel() {
  const [jiraAction, setJiraAction] = useState<'backfill' | 'import' | null>(null);
  const [jiraMessage, setJiraMessage] = useState<string | null>(null);
  const [backfillWorkspaceId, setBackfillWorkspaceId] = useState('');
  const [importProject, setImportProject] = useState<string>('TCOC');
  const [importUpdatedFrom, setImportUpdatedFrom] = useState('');
  const [importUpdatedTo, setImportUpdatedTo] = useState('');
  const [clearImportBusy, setClearImportBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [clearModalStep, setClearModalStep] = useState<0 | 1 | 2>(0);
  const [clearPhrase, setClearPhrase] = useState('');
  const [clearPhraseError, setClearPhraseError] = useState<string | null>(null);

  const clearZBackdrop = 1100;
  const clearZContent = 1101;

  async function runBackfill() {
    setJiraAction('backfill');
    setJiraMessage(null);
    setError(null);
    try {
      const r = await jiraTcocBackfillWorkspaceLinks(backfillWorkspaceId.trim() || undefined);
      setJiraMessage(JSON.stringify(r));
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Backfill failed');
    } finally {
      setJiraAction(null);
    }
  }

  async function runImportTickets() {
    setJiraAction('import');
    setJiraMessage(null);
    setError(null);
    try {
      const r = await jiraTicketsImportOnce({
        project_key: importProject.trim(),
        updated_from: importUpdatedFrom.trim() || undefined,
        updated_to: importUpdatedTo.trim() || undefined,
      });
      setJiraMessage(JSON.stringify(r));
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Import failed');
    } finally {
      setJiraAction(null);
    }
  }

  function openClearImportModal() {
    setClearPhrase('');
    setClearPhraseError(null);
    setError(null);
    setClearModalStep(1);
  }

  function closeClearImportModal() {
    if (clearImportBusy) return;
    setClearModalStep(0);
    setClearPhrase('');
    setClearPhraseError(null);
  }

  async function executeClearImported() {
    if (clearPhrase.trim() !== CLEAR_JIRA_INCIDENT_IMPORT_CONFIRM) {
      setClearPhraseError('Confirmation phrase did not match');
      return;
    }
    setClearPhraseError(null);
    setClearModalStep(0);
    setClearPhrase('');
    setClearImportBusy(true);
    setJiraMessage(null);
    setError(null);
    try {
      const r = await clearIncidentJiraImportedData();
      setJiraMessage(JSON.stringify(r, null, 2));
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Clear failed');
    } finally {
      setClearImportBusy(false);
    }
  }

  return (
    <div style={{ paddingTop: 0 }}>
      <p style={{ margin: '0 0 16px', fontSize: 13, color: '#6b7280', lineHeight: 1.55 }}>
        Ticket import (by Jira project and optional <code style={{ fontSize: 12 }}>updated</code>{' '}
        date range), workspace–issue backfill, and destructive reset of imported Jira data.
      </p>

      <div
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: 10,
          alignItems: 'center',
          marginBottom: 16,
          padding: '12px 14px',
          background: '#f9fafb',
          borderRadius: 10,
          border: '1px solid #e5e7eb',
        }}
      >
        <span style={{ fontSize: 13, color: '#6b7280', marginRight: 4 }}>Jira / workspace link</span>
        <input
          type="text"
          placeholder="Optional: only backfill this workspace id, e.g. ws-1778062995582-4e7a356c9"
          value={backfillWorkspaceId}
          onChange={(e) => setBackfillWorkspaceId(e.target.value)}
          style={{
            flex: '1 1 200px',
            maxWidth: 360,
            padding: '8px 12px',
            borderRadius: 8,
            border: '1px solid #e5e7eb',
            fontSize: 13,
            fontFamily: 'ui-monospace, monospace',
          }}
        />
        <button
          type="button"
          disabled={jiraAction !== null}
          onClick={runBackfill}
          style={{
            padding: '8px 14px',
            borderRadius: 8,
            border: '1px solid #c7d2fe',
            background: '#fff',
            color: '#4338ca',
            fontWeight: 600,
            fontSize: 13,
            cursor: jiraAction !== null ? 'wait' : 'pointer',
            opacity: jiraAction !== null ? 0.65 : 1,
          }}
        >
          {jiraAction === 'backfill' ? 'Backfilling…' : 'Backfill workspace issue links'}
        </button>
      </div>

      <div
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: 10,
          alignItems: 'center',
          marginBottom: 16,
          padding: '12px 14px',
          background: '#f9fafb',
          borderRadius: 10,
          border: '1px solid #e5e7eb',
        }}
      >
        <span style={{ fontSize: 13, color: '#6b7280', fontWeight: 600 }}>Import tickets</span>
        <label style={{ fontSize: 13, color: '#374151', display: 'flex', alignItems: 'center', gap: 6 }}>
          Project
          <select
            value={IMPORT_PROJECT_OPTIONS.includes(importProject as (typeof IMPORT_PROJECT_OPTIONS)[number]) ? importProject : 'CUSTOM'}
            onChange={(e) => {
              const v = e.target.value;
              if (v === 'CUSTOM') setImportProject('');
              else setImportProject(v);
            }}
            style={{
              padding: '8px 10px',
              borderRadius: 8,
              border: '1px solid #e5e7eb',
              fontSize: 13,
              minWidth: 88,
            }}
          >
            {IMPORT_PROJECT_OPTIONS.map((pk) => (
              <option key={pk} value={pk}>
                {pk}
              </option>
            ))}
            <option value="CUSTOM">Other…</option>
          </select>
        </label>
        {(importProject === '' ||
          !IMPORT_PROJECT_OPTIONS.includes(importProject as (typeof IMPORT_PROJECT_OPTIONS)[number])) && (
          <input
            type="text"
            placeholder="Project key, e.g. TCOC"
            value={importProject}
            onChange={(e) => setImportProject(e.target.value.toUpperCase())}
            style={{
              flex: '1 1 120px',
              maxWidth: 120,
              padding: '8px 12px',
              borderRadius: 8,
              border: '1px solid #e5e7eb',
              fontSize: 13,
              fontFamily: 'ui-monospace, monospace',
            }}
          />
        )}
        <label style={{ fontSize: 13, color: '#374151', display: 'flex', alignItems: 'center', gap: 6 }}>
          Updated from
          <input
            type="date"
            value={importUpdatedFrom}
            onChange={(e) => setImportUpdatedFrom(e.target.value)}
            style={{
              padding: '8px 10px',
              borderRadius: 8,
              border: '1px solid #e5e7eb',
              fontSize: 13,
            }}
          />
        </label>
        <label style={{ fontSize: 13, color: '#374151', display: 'flex', alignItems: 'center', gap: 6 }}>
          Updated to
          <input
            type="date"
            value={importUpdatedTo}
            onChange={(e) => setImportUpdatedTo(e.target.value)}
            style={{
              padding: '8px 10px',
              borderRadius: 8,
              border: '1px solid #e5e7eb',
              fontSize: 13,
            }}
          />
        </label>
        <button
          type="button"
          disabled={jiraAction !== null || !importProject.trim()}
          onClick={() => void runImportTickets()}
          style={{
            padding: '8px 14px',
            borderRadius: 8,
            border: '1px solid #c7d2fe',
            background: '#eef2ff',
            color: '#3730a3',
            fontWeight: 600,
            fontSize: 13,
            cursor: jiraAction !== null ? 'wait' : 'pointer',
            opacity: jiraAction !== null || !importProject.trim() ? 0.65 : 1,
          }}
        >
          {jiraAction === 'import' ? 'Importing…' : 'Import tickets'}
        </button>
      </div>
      <p style={{ margin: '-8px 0 16px', fontSize: 12, color: '#9ca3af', lineHeight: 1.5 }}>
        Leave both dates empty to import the same rolling window as the scheduled job (last 25 hours).
        When both are set, the range is inclusive by calendar day (Jira <code style={{ fontSize: 11 }}>updated</code>).
      </p>

      <div
        style={{
          display: 'flex',
          flexWrap: 'wrap',
          gap: 10,
          alignItems: 'center',
          marginBottom: 16,
          padding: '10px 14px',
          borderRadius: 10,
          border: '1px solid #fecaca',
          background: '#fff1f2',
        }}
      >
        <span style={{ fontSize: 13, color: '#991b1b', fontWeight: 600, marginRight: 4 }}>
          Danger zone
        </span>
        <button
          type="button"
          disabled={jiraAction !== null || clearImportBusy}
          onClick={openClearImportModal}
          style={{
            padding: '8px 14px',
            borderRadius: 8,
            border: '1px solid #f87171',
            background: '#fff',
            color: '#b91c1c',
            fontWeight: 600,
            fontSize: 13,
            cursor: jiraAction !== null || clearImportBusy ? 'wait' : 'pointer',
            opacity: jiraAction !== null || clearImportBusy ? 0.65 : 1,
          }}
        >
          {clearImportBusy ? 'Clearing…' : 'Clear imported Jira data and incidents'}
        </button>
      </div>

      {jiraMessage && (
        <div
          style={{
            padding: 10,
            borderRadius: 8,
            background: '#ecfdf5',
            color: '#047857',
            marginBottom: 16,
            fontSize: 12,
            fontFamily: 'ui-monospace, monospace',
            wordBreak: 'break-all',
          }}
        >
          {jiraMessage}
        </div>
      )}

      {error && (
        <div
          style={{
            padding: 12,
            borderRadius: 8,
            background: '#fef2f2',
            color: '#991b1b',
            marginBottom: 16,
            fontSize: 14,
          }}
        >
          {error}
        </div>
      )}

      <AdminModal
        opened={clearModalStep > 0}
        onClose={closeClearImportModal}
        disableBackdropClose={clearImportBusy}
        title={clearModalStep === 1 ? 'Clear imported data?' : 'Confirm phrase'}
        width={clearModalStep === 1 ? 460 : 500}
        zIndexBackdrop={clearZBackdrop}
        zIndexContent={clearZContent}
      >
        {clearModalStep === 1 && (
          <>
            <p
              style={{
                margin: '0 0 20px',
                fontSize: 14,
                color: '#4b5563',
                lineHeight: 1.6,
                whiteSpace: 'pre-wrap',
              }}
            >
              {
                'This will delete: all jira_tickets rows, incidents and their issue/workspace links, workspace_jira_links, Jira import cursors, and dossier audit logs.\n\nWorkspaces, workspace_sources, and user accounts will NOT be removed.\n\nThis cannot be undone.'
              }
            </p>
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, flexWrap: 'wrap' }}>
              <button
                type="button"
                onClick={closeClearImportModal}
                style={{
                  padding: '8px 16px',
                  borderRadius: 8,
                  border: '1px solid #e5e7eb',
                  background: '#fff',
                  color: '#374151',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: 'pointer',
                }}
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={() => {
                  setError(null);
                  setClearPhraseError(null);
                  setClearModalStep(2);
                }}
                style={{
                  padding: '8px 16px',
                  borderRadius: 8,
                  border: 'none',
                  background: 'linear-gradient(135deg, #dc2626, #b91c1c)',
                  color: '#fff',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: 'pointer',
                }}
              >
                Continue
              </button>
            </div>
          </>
        )}
        {clearModalStep === 2 && (
          <>
            <p style={{ margin: '0 0 8px', fontSize: 14, color: '#4b5563', lineHeight: 1.5 }}>
              Type this exactly in the box below:
            </p>
            {clearPhraseError && (
              <p style={{ margin: '0 0 10px', fontSize: 13, color: '#b91c1c' }}>
                {clearPhraseError}
              </p>
            )}
            <code
              style={{
                display: 'block',
                marginBottom: 12,
                padding: '10px 12px',
                background: '#f3f4f6',
                borderRadius: 8,
                fontSize: 13,
                fontFamily: 'ui-monospace, monospace',
                color: '#1f2937',
                wordBreak: 'break-all',
              }}
            >
              {CLEAR_JIRA_INCIDENT_IMPORT_CONFIRM}
            </code>
            <input
              type="text"
              value={clearPhrase}
              onChange={(e) => {
                setClearPhrase(e.target.value);
                setClearPhraseError(null);
              }}
              placeholder="Confirmation phrase"
              autoFocus
              style={{
                width: '100%',
                boxSizing: 'border-box',
                padding: '10px 12px',
                borderRadius: 8,
                border: '1px solid #e5e7eb',
                fontSize: 14,
                fontFamily: 'ui-monospace, monospace',
                marginBottom: 20,
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') void executeClearImported();
              }}
            />
            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10, flexWrap: 'wrap' }}>
              <button
                type="button"
                onClick={() => {
                  setError(null);
                  setClearPhraseError(null);
                  setClearPhrase('');
                  setClearModalStep(1);
                }}
                disabled={clearImportBusy}
                style={{
                  padding: '8px 16px',
                  borderRadius: 8,
                  border: '1px solid #e5e7eb',
                  background: '#fff',
                  color: '#374151',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: clearImportBusy ? 'wait' : 'pointer',
                }}
              >
                Back
              </button>
              <button
                type="button"
                onClick={closeClearImportModal}
                disabled={clearImportBusy}
                style={{
                  padding: '8px 16px',
                  borderRadius: 8,
                  border: '1px solid #e5e7eb',
                  background: '#fff',
                  color: '#374151',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: clearImportBusy ? 'wait' : 'pointer',
                }}
              >
                Cancel
              </button>
              <button
                type="button"
                disabled={clearImportBusy}
                onClick={() => void executeClearImported()}
                style={{
                  padding: '8px 16px',
                  borderRadius: 8,
                  border: 'none',
                  background: 'linear-gradient(135deg, #dc2626, #b91c1c)',
                  color: '#fff',
                  fontWeight: 600,
                  fontSize: 14,
                  cursor: clearImportBusy ? 'wait' : 'pointer',
                  opacity: clearImportBusy ? 0.7 : 1,
                }}
              >
                {clearImportBusy ? 'Clearing…' : 'Clear data'}
              </button>
            </div>
          </>
        )}
      </AdminModal>
    </div>
  );
}
