import { useMemo, useState } from 'react';
import { SegmentedTabs, Tabs } from '@cameleer/design-system';
import type { Deployment } from '../../../../api/queries/admin/apps';
import { MonitoringTab } from '../ConfigTabs/MonitoringTab';
import { ResourcesTab } from '../ConfigTabs/ResourcesTab';
import { VariablesTab } from '../ConfigTabs/VariablesTab';
import { SensitiveKeysTab } from '../ConfigTabs/SensitiveKeysTab';
import { defaultForm, type DeploymentPageFormState } from '../hooks/useDeploymentPageState';
import { snapshotToForm } from './snapshotToForm';
import { fieldDiff, type FieldDiff } from './diff';
import styles from './CheckpointDetailDrawer.module.css';

interface Props {
  deployment: Deployment;
  appSlug: string;
  envSlug: string;
  archived: boolean;
  currentForm?: DeploymentPageFormState;
}

type Mode = 'snapshot' | 'diff';
type SubTab = 'monitoring' | 'resources' | 'variables' | 'sensitive';

export function ConfigPanel({ deployment, archived, currentForm }: Props) {
  const [mode, setMode] = useState<Mode>('snapshot');
  const [subTab, setSubTab] = useState<SubTab>('resources');

  const snapshot = deployment.deployedConfigSnapshot;
  const snapshotForm = useMemo(
    () => (snapshot ? snapshotToForm(snapshot, defaultForm) : defaultForm),
    [snapshot],
  );

  const diff: FieldDiff[] = useMemo(
    () => (mode === 'diff' && currentForm ? fieldDiff(snapshotForm, currentForm) : []),
    [mode, snapshotForm, currentForm],
  );

  const counts = useMemo(() => {
    const c: Record<SubTab, number> = { monitoring: 0, resources: 0, variables: 0, sensitive: 0 };
    for (const d of diff) {
      const root = d.path.split('.')[0].split('[')[0];
      if (root === 'monitoring') c.monitoring++;
      else if (root === 'resources') c.resources++;
      else if (root === 'variables') c.variables++;
      else if (root === 'sensitiveKeys') c.sensitive++;
    }
    return c;
  }, [diff]);

  if (!snapshot) {
    return <div className={styles.emptyState}>This deployment has no config snapshot.</div>;
  }

  const showToggle = !archived && !!currentForm;

  return (
    <div>
      {showToggle && (
        <SegmentedTabs
          tabs={[
            { value: 'snapshot', label: 'Snapshot' },
            { value: 'diff', label: `Diff vs current${diff.length ? ` (${diff.length})` : ''}` },
          ]}
          active={mode}
          onChange={(m) => setMode(m as Mode)}
        />
      )}

      <Tabs
        active={subTab}
        onChange={(t) => setSubTab(t as SubTab)}
        tabs={[
          { value: 'resources', label: `Resources${counts.resources ? ` (${counts.resources})` : ''}` },
          { value: 'monitoring', label: `Monitoring${counts.monitoring ? ` (${counts.monitoring})` : ''}` },
          { value: 'variables', label: `Variables${counts.variables ? ` (${counts.variables})` : ''}` },
          { value: 'sensitive', label: `Sensitive Keys${counts.sensitive ? ` (${counts.sensitive})` : ''}` },
        ]}
      />

      <div style={{ marginTop: 12 }}>
        {mode === 'snapshot' && (
          <>
            {subTab === 'resources' && (
              <ResourcesTab value={snapshotForm.resources} onChange={() => {}} disabled isProd={false} />
            )}
            {subTab === 'monitoring' && (
              <MonitoringTab value={snapshotForm.monitoring} onChange={() => {}} disabled />
            )}
            {subTab === 'variables' && (
              <VariablesTab value={snapshotForm.variables} onChange={() => {}} disabled />
            )}
            {subTab === 'sensitive' && (
              <SensitiveKeysTab value={snapshotForm.sensitiveKeys} onChange={() => {}} disabled />
            )}
          </>
        )}

        {mode === 'diff' && (
          <DiffView diffs={diff.filter((d) => filterTab(d.path, subTab))} />
        )}
      </div>
    </div>
  );
}

function filterTab(path: string, tab: SubTab): boolean {
  const root = path.split('.')[0].split('[')[0];
  if (tab === 'sensitive') return root === 'sensitiveKeys';
  return root === tab;
}

function DiffView({ diffs }: { diffs: FieldDiff[] }) {
  if (diffs.length === 0) {
    return <div className={styles.emptyState}>No differences in this section.</div>;
  }
  return (
    <div className={styles.diffList}>
      {diffs.map((d) => (
        <div key={d.path} className={styles.diffEntry}>
          <div className={styles.diffPath}>{d.path}</div>
          <div className={styles.diffRemoved}>- {JSON.stringify(d.oldValue)}</div>
          <div className={styles.diffAdded}>+ {JSON.stringify(d.newValue)}</div>
        </div>
      ))}
    </div>
  );
}
