'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Slider } from '@/components/ui/slider';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PaletteGrid } from '@/components/pastel/PaletteGrid';
import { ExportMenu } from '@/components/pastel/ExportMenu';
import { AppPage } from '@/components/layout/AppPage';
import { useLighten, useDarken, useSaturate, useDesaturate, useRotate } from '@/lib/pastel/api/queries';
import { Loader2, Upload, Download } from 'lucide-react';
import { toast } from 'sonner';

type Operation = 'lighten' | 'darken' | 'saturate' | 'desaturate' | 'rotate';

export default function BatchPage() {
  const [inputColors, setInputColors] = useState('');
  const [operation, setOperation] = useState<Operation>('lighten');
  const [amount, setAmount] = useState(0.2);
  const [outputColors, setOutputColors] = useState<string[]>([]);

  const lightenMutation = useLighten();
  const darkenMutation = useDarken();
  const saturateMutation = useSaturate();
  const desaturateMutation = useDesaturate();
  const rotateMutation = useRotate();

  const parseColors = (text: string): string[] => {
    // Parse colors from text (one per line, or comma-separated)
    return text
      .split(/[\n,]/)
      .map((c) => c.trim())
      .filter((c) => c.length > 0 && c.match(/^#?[0-9a-fA-F]{3,8}$/));
  };

  const handleProcess = async () => {
    const colors = parseColors(inputColors);

    if (colors.length === 0) {
      toast.error('No valid colors found');
      return;
    }

    if (colors.length > 100) {
      toast.error('Maximum 100 colors allowed');
      return;
    }

    try {
      let result;

      switch (operation) {
        case 'lighten':
          result = await lightenMutation.mutateAsync({ colors, amount });
          break;
        case 'darken':
          result = await darkenMutation.mutateAsync({ colors, amount });
          break;
        case 'saturate':
          result = await saturateMutation.mutateAsync({ colors, amount });
          break;
        case 'desaturate':
          result = await desaturateMutation.mutateAsync({ colors, amount });
          break;
        case 'rotate':
          result = await rotateMutation.mutateAsync({ colors, amount: amount * 360 });
          break;
      }

      // Extract output colors from the result
      const processed = result.colors.map((c) => c.output);
      setOutputColors(processed);
      toast.success(`Processed ${processed.length} colors`);
    } catch (error) {
      toast.error('Failed to process colors');
      console.error(error);
    }
  };

  const isPending =
    lightenMutation.isPending ||
    darkenMutation.isPending ||
    saturateMutation.isPending ||
    desaturateMutation.isPending ||
    rotateMutation.isPending;

  return (
    <AppPage
      title="Batch Operations"
      description="Process multiple colors at once with manipulation operations"
    >
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Input */}
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Input Colors</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-muted-foreground mb-4">
                  Enter colors (one per line or comma-separated). Supports hex format
                </p>

                <Textarea
                  value={inputColors}
                  onChange={(e) => setInputColors(e.target.value)}
                  placeholder="#ff0099, #00ff99, #9900ff&#10;#ff5533&#10;#3355ff"
                  className="h-48 font-mono"
                />

                <p className="text-xs text-muted-foreground mt-2">
                  {parseColors(inputColors).length} valid colors found
                </p>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Operation</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <Select
                  value={operation}
                  onValueChange={(value) => setOperation(value as Operation)}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select operation" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="lighten">Lighten</SelectItem>
                    <SelectItem value="darken">Darken</SelectItem>
                    <SelectItem value="saturate">Saturate</SelectItem>
                    <SelectItem value="desaturate">Desaturate</SelectItem>
                    <SelectItem value="rotate">Rotate Hue</SelectItem>
                  </SelectContent>
                </Select>

                <div className="space-y-4 pt-2">
                  <div className="flex items-center justify-between">
                    <label className="text-sm font-medium">
                      Amount
                    </label>
                    <span className="text-xs text-muted-foreground">
                      {operation === 'rotate' ? (amount * 360).toFixed(0) + '°' : (amount * 100).toFixed(0) + '%'}
                    </span>
                  </div>
                  <Slider
                    min={0}
                    max={1}
                    step={0.01}
                    value={[amount]}
                    onValueChange={(vals) => setAmount(vals[0])}
                  />
                </div>

                <Button
                  onClick={handleProcess}
                  disabled={isPending || parseColors(inputColors).length === 0}
                  className="w-full"
                >
                  {isPending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Processing..
                    </>
                  ) : (
                    <>
                      <Upload className="mr-2 h-4 w-4" />
                      Process Colors
                    </>
                  )}
                </Button>
              </CardContent>
            </Card>
          </div>

          {/* Output */}
          <div className="space-y-6">
            {outputColors.length > 0 ? (
              <>
                <Card>
                  <CardHeader>
                    <CardTitle>
                      Output Colors ({outputColors.length})
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <PaletteGrid colors={outputColors} />
                  </CardContent>
                </Card>

                <Card>
                  <CardContent className="pt-6">
                    <ExportMenu colors={outputColors} />
                  </CardContent>
                </Card>
              </>
            ) : (
              <Card>
                <CardContent className="p-12 text-center text-muted-foreground">
                  <Download className="h-12 w-12 mx-auto mb-4 opacity-50" />
                  <p>Enter colors and click Process to see results</p>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
    </AppPage>
  );
}
