'use client';

import { useState } from 'react';
import { ColorPicker } from '@/components/pastel/ColorPicker';
import { PaletteGrid } from '@/components/pastel/PaletteGrid';
import { ExportMenu } from '@/components/pastel/ExportMenu';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { AppPage } from '@/components/layout/AppPage';
import { useGenerateGradient } from '@/lib/pastel/api/queries';
import { Loader2, Plus, X } from 'lucide-react';
import { toast } from 'sonner';

export default function GradientPage() {
  const [stops, setStops] = useState<string[]>(['#ff0099', '#0099ff']);
  const [count, setCount] = useState(10);
  const [gradient, setGradient] = useState<string[]>([]);

  const generateMutation = useGenerateGradient();

  const handleGenerate = async () => {
    try {
      const result = await generateMutation.mutateAsync({
        stops,
        count,
      });
      setGradient(result.gradient);
      toast.success(`Generated ${result.gradient.length} colors`);
    } catch (error) {
      toast.error('Failed to generate gradient');
    }
  };

  const addStop = () => {
    setStops([...stops, '#000000']);
  };

  const removeStop = (index: number) => {
    if (stops.length > 2) {
      setStops(stops.filter((_, i) => i !== index));
    }
  };

  const updateStop = (index: number, color: string) => {
    const newStops = [...stops];
    newStops[index] = color;
    setStops(newStops);
  };

  return (
    <AppPage
      title="Gradient Creator"
      description="Create smooth color gradients with multiple stops"
    >
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {/* Controls */}
          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>Color Stops</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="space-y-4">
                  {stops.map((stop, index) => (
                    <div key={index} className="flex items-start gap-3">
                      <div className="flex-1">
                        <ColorPicker
                          color={stop}
                          onChange={(color) => updateStop(index, color)}
                        />
                      </div>
                      {stops.length > 2 && (
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => removeStop(index)}
                          className="mt-8"
                        >
                          <X className="h-4 w-4" />
                        </Button>
                      )}
                    </div>
                  ))}
                  <Button onClick={addStop} variant="outline" className="w-full">
                    <Plus className="h-4 w-4 mr-2" />
                    Add Stop
                  </Button>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Settings</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div>
                  <label htmlFor="count" className="text-sm font-medium mb-2 block">
                    Number of Colors
                  </label>
                  <Input
                    id="count"
                    type="number"
                    min={2}
                    max={1000}
                    value={count}
                    onChange={(e) => setCount(parseInt(e.target.value))}
                  />
                </div>

                <Button
                  onClick={handleGenerate}
                  disabled={generateMutation.isPending || stops.length < 2}
                  className="w-full"
                >
                  {generateMutation.isPending ? (
                    <>
                      <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                      Generating..
                    </>
                  ) : (
                    'Generate Gradient'
                  )}
                </Button>
              </CardContent>
            </Card>
          </div>

          {/* Preview */}
          <div className="space-y-6">
            {gradient && gradient.length > 0 && (
              <>
                <Card>
                  <CardHeader>
                    <CardTitle>Gradient Preview</CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div
                      className="h-32 rounded-lg"
                      style={{
                        background: `linear-gradient(to right, ${gradient.join(', ')})`,
                      }}
                    />
                  </CardContent>
                </Card>

                <Card>
                  <CardHeader>
                    <CardTitle>
                      Colors ({gradient.length})
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <PaletteGrid colors={gradient} />
                  </CardContent>
                </Card>

                <Card>
                  <CardContent className="pt-6">
                    <ExportMenu colors={gradient} />
                  </CardContent>
                </Card>
              </>
            )}
          </div>
        </div>
    </AppPage>
  );
}
