'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,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Switch,
} from '@spoon/ui';

type MaintenanceMode = 'watch' | 'auto_pr' | 'paused';
type SyncCadence = 'daily' | 'weekly' | 'manual';
type ProductionRefStrategy =
  | 'default_branch'
  | 'latest_release'
  | 'tag_pattern';

export const SpoonSettingsForm = ({
  spoon,
  settings,
}: {
  spoon: Doc<'spoons'>;
  settings?: Doc<'spoonSettings'> | null;
}) => {
  const update = useMutation(api.spoonSettings.update);
  const updateSpoonSettings = useMutation(api.spoons.updateSettings);
  const [syncCadence, setSyncCadence] = useState<SyncCadence>(
    spoon.syncCadence,
  );
  const [maintenanceMode, setMaintenanceMode] = useState<MaintenanceMode>(
    spoon.maintenanceMode,
  );
  const [productionRefStrategy, setProductionRefStrategy] =
    useState<ProductionRefStrategy>(spoon.productionRefStrategy);
  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 Promise.all([
        updateSpoonSettings({
          spoonId: spoon._id,
          syncCadence,
          maintenanceMode,
          productionRefStrategy,
        }),
        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 maintenance threads',
      value: autoReviewEnabled,
      onChange: setAutoReviewEnabled,
    },
    {
      label: 'Auto sync',
      value: autoSyncEnabled,
      onChange: setAutoSyncEnabled,
    },
    {
      label: 'Require low-risk thread decision 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 className='grid gap-2'>
            <Label>Sync cadence</Label>
            <Select
              value={syncCadence}
              onValueChange={(value) => setSyncCadence(value as SyncCadence)}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value='daily'>Daily</SelectItem>
                <SelectItem value='weekly'>Weekly</SelectItem>
                <SelectItem value='manual'>Manual</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className='grid gap-2'>
            <Label>Maintenance mode</Label>
            <Select
              value={maintenanceMode}
              onValueChange={(value) =>
                setMaintenanceMode(value as MaintenanceMode)
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value='watch'>Watch only</SelectItem>
                <SelectItem value='auto_pr'>Prepare merge requests</SelectItem>
                <SelectItem value='paused'>Paused</SelectItem>
              </SelectContent>
            </Select>
          </div>
          <div className='grid gap-2'>
            <Label>Production ref</Label>
            <Select
              value={productionRefStrategy}
              onValueChange={(value) =>
                setProductionRefStrategy(value as ProductionRefStrategy)
              }
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value='default_branch'>Default branch</SelectItem>
                <SelectItem value='latest_release'>Latest release</SelectItem>
                <SelectItem value='tag_pattern'>Tag pattern</SelectItem>
              </SelectContent>
            </Select>
          </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>
  );
};
