'use client';

import { useState } from 'react';
import { useMutation } from 'convex/react';
import { toast } from 'sonner';

import type { Doc } from '@spoon/backend/convex/_generated/dataModel.js';
import { api } from '@spoon/backend/convex/_generated/api.js';
import {
  Button,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  Label,
  Switch,
} from '@spoon/ui';

export const SpoonSettingsForm = ({
  spoon,
  settings,
}: {
  spoon: Doc<'spoons'>;
  settings?: Doc<'spoonSettings'> | null;
}) => {
  const update = useMutation(api.spoonSettings.update);
  const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(
    settings?.autoRefreshEnabled ?? true,
  );
  const [autoReviewEnabled, setAutoReviewEnabled] = useState(
    settings?.autoReviewEnabled ?? true,
  );
  const [autoSyncEnabled, setAutoSyncEnabled] = useState(
    settings?.autoSyncEnabled ?? false,
  );
  const [requireAiLowRiskForSync, setRequireAiLowRiskForSync] = useState(
    settings?.requireAiLowRiskForSync ?? true,
  );
  const [requireCleanCompareForSync, setRequireCleanCompareForSync] = useState(
    settings?.requireCleanCompareForSync ?? true,
  );

  const save = async () => {
    try {
      await update({
        spoonId: spoon._id,
        autoRefreshEnabled,
        autoReviewEnabled,
        autoSyncEnabled,
        requireAiLowRiskForSync,
        requireCleanCompareForSync,
      });
      toast.success('Spoon settings saved.');
    } catch (error) {
      console.error(error);
      toast.error('Could not save settings.');
    }
  };

  const rows = [
    {
      label: 'Auto refresh',
      value: autoRefreshEnabled,
      onChange: setAutoRefreshEnabled,
    },
    {
      label: 'Auto AI review',
      value: autoReviewEnabled,
      onChange: setAutoReviewEnabled,
    },
    {
      label: 'Auto sync',
      value: autoSyncEnabled,
      onChange: setAutoSyncEnabled,
    },
    {
      label: 'Require low AI risk for sync',
      value: requireAiLowRiskForSync,
      onChange: setRequireAiLowRiskForSync,
    },
    {
      label: 'Require clean compare for sync',
      value: requireCleanCompareForSync,
      onChange: setRequireCleanCompareForSync,
    },
  ];

  return (
    <Card className='shadow-none'>
      <CardHeader>
        <CardTitle className='text-base'>Maintenance settings</CardTitle>
      </CardHeader>
      <CardContent className='space-y-4'>
        <div className='grid gap-3 md:grid-cols-2'>
          <div>
            <p className='text-muted-foreground text-xs'>Sync cadence</p>
            <p className='font-medium'>{spoon.syncCadence}</p>
          </div>
          <div>
            <p className='text-muted-foreground text-xs'>Maintenance mode</p>
            <p className='font-medium'>
              {spoon.maintenanceMode.replaceAll('_', ' ')}
            </p>
          </div>
          <div>
            <p className='text-muted-foreground text-xs'>Production ref</p>
            <p className='font-medium'>
              {spoon.productionRefStrategy.replaceAll('_', ' ')}
            </p>
          </div>
        </div>
        <div className='space-y-3'>
          {rows.map((row) => (
            <div
              key={row.label}
              className='flex items-center justify-between gap-4 border-t pt-3'
            >
              <Label>{row.label}</Label>
              <Switch checked={row.value} onCheckedChange={row.onChange} />
            </div>
          ))}
        </div>
        <Button onClick={save}>Save settings</Button>
      </CardContent>
    </Card>
  );
};
