'use client';

import { useState, useEffect } from 'react';
import { Header } from '@/components/header';
import { MainLayout } from '@/components/main-layout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { PromptTextarea } from '@/components/prompt-textarea';
import { Label } from '@/components/ui/label';
import { Card, CardContent } from '@/components/ui/card';
import { apiClient, type GenerationRequest, type JobInfo, type ModelInfo } from '@/lib/api';
import { Loader2, Download, X } from 'lucide-react';
import { downloadImage } from '@/lib/utils';
import { useLocalStorage } from '@/lib/hooks';

const defaultFormData: GenerationRequest = {
  prompt: '',
  negative_prompt: '',
  width: 512,
  height: 512,
  steps: 20,
  cfg_scale: 7.5,
  seed: '',
  sampling_method: 'euler_a',
  scheduler: 'default',
  batch_count: 1,
};

export default function Text2ImgPage() {
  const [formData, setFormData] = useLocalStorage<GenerationRequest>(
    'text2img-form-data',
    defaultFormData
  );

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [jobInfo, setJobInfo] = useState<JobInfo | null>(null);
  const [generatedImages, setGeneratedImages] = useState<string[]>([]);
  const [samplers, setSamplers] = useState<Array<{ name: string; description: string }>>([]);
  const [schedulers, setSchedulers] = useState<Array<{ name: string; description: string }>>([]);
  const [vaeModels, setVaeModels] = useState<ModelInfo[]>([]);
  const [selectedVae, setSelectedVae] = useState<string>('');
  const [loraModels, setLoraModels] = useState<string[]>([]);
  const [embeddings, setEmbeddings] = useState<string[]>([]);

  useEffect(() => {
    const loadOptions = async () => {
      try {
        const [samplersData, schedulersData, models, loras, embeds] = await Promise.all([
          apiClient.getSamplers(),
          apiClient.getSchedulers(),
          apiClient.getModels('vae'),
          apiClient.getModels('lora'),
          apiClient.getModels('embedding'),
        ]);
        setSamplers(samplersData);
        setSchedulers(schedulersData);
        setVaeModels(models);
        setLoraModels(loras.map(m => m.name));
        setEmbeddings(embeds.map(m => m.name));
      } catch (err) {
        console.error('Failed to load options:', err);
      }
    };
    loadOptions();
  }, []);

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: name === 'prompt' || name === 'negative_prompt' || name === 'seed' || name === 'sampling_method'
        ? value
        : Number(value),
    }));
  };

  const pollJobStatus = async (jobId: string) => {
    const maxAttempts = 300; // 5 minutes with 1 second interval
    let attempts = 0;

    const poll = async () => {
      try {
        const status = await apiClient.getJobStatus(jobId);
        setJobInfo(status);

        if (status.status === 'completed' && status.result?.images) {
          setGeneratedImages(status.result.images);
          setLoading(false);
        } else if (status.status === 'failed') {
          setError(status.error || 'Generation failed');
          setLoading(false);
        } else if (status.status === 'cancelled') {
          setError('Generation was cancelled');
          setLoading(false);
        } else if (attempts < maxAttempts) {
          attempts++;
          setTimeout(poll, 1000);
        } else {
          setError('Job polling timeout');
          setLoading(false);
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Failed to check job status');
        setLoading(false);
      }
    };

    poll();
  };

  const handleGenerate = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError(null);
    setGeneratedImages([]);
    setJobInfo(null);

    try {
      const job = await apiClient.text2img(formData);
      setJobInfo(job);
      const jobId = job.request_id || job.id;
      if (jobId) {
        await pollJobStatus(jobId);
      } else {
        setError('No job ID returned from server');
        setLoading(false);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to generate image');
      setLoading(false);
    }
  };

  const handleCancel = async () => {
    const jobId = jobInfo?.request_id || jobInfo?.id;
    if (jobId) {
      try {
        await apiClient.cancelJob(jobId);
        setLoading(false);
        setError('Generation cancelled');
      } catch (err) {
        console.error('Failed to cancel job:', err);
      }
    }
  };

  return (
    <MainLayout>
      <Header title="Text to Image" description="Generate images from text prompts" />
      <div className="container mx-auto p-6">
        <div className="grid gap-6 lg:grid-cols-2">
          {/* Left Panel - Form */}
          <Card>
            <CardContent className="pt-6">
              <form onSubmit={handleGenerate} className="space-y-4">
                <div className="space-y-2">
                  <Label htmlFor="prompt">Prompt *</Label>
                  <PromptTextarea
                    value={formData.prompt}
                    onChange={(value) => setFormData({ ...formData, prompt: value })}
                    placeholder="a beautiful landscape with mountains and a lake, sunset, highly detailed..."
                    rows={4}
                    loras={loraModels}
                    embeddings={embeddings}
                  />
                  <p className="text-xs text-muted-foreground">
                    Tip: Use &lt;lora:name:weight&gt; for LoRAs (e.g., &lt;lora:myLora:0.8&gt;) and embedding names directly
                  </p>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="negative_prompt">Negative Prompt</Label>
                  <PromptTextarea
                    value={formData.negative_prompt || ''}
                    onChange={(value) => setFormData({ ...formData, negative_prompt: value })}
                    placeholder="blurry, low quality, distorted..."
                    rows={2}
                  />
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="width">Width</Label>
                    <Input
                      id="width"
                      name="width"
                      type="number"
                      value={formData.width}
                      onChange={handleInputChange}
                      step={64}
                      min={256}
                      max={2048}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="height">Height</Label>
                    <Input
                      id="height"
                      name="height"
                      type="number"
                      value={formData.height}
                      onChange={handleInputChange}
                      step={64}
                      min={256}
                      max={2048}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor="steps">Steps</Label>
                    <Input
                      id="steps"
                      name="steps"
                      type="number"
                      value={formData.steps}
                      onChange={handleInputChange}
                      min={1}
                      max={150}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="cfg_scale">CFG Scale</Label>
                    <Input
                      id="cfg_scale"
                      name="cfg_scale"
                      type="number"
                      value={formData.cfg_scale}
                      onChange={handleInputChange}
                      step={0.5}
                      min={1}
                      max={30}
                    />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="seed">Seed (optional)</Label>
                  <Input
                    id="seed"
                    name="seed"
                    value={formData.seed}
                    onChange={handleInputChange}
                    placeholder="Leave empty for random"
                  />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="sampling_method">Sampling Method</Label>
                  <select
                    id="sampling_method"
                    name="sampling_method"
                    value={formData.sampling_method}
                    onChange={handleInputChange}
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  >
                    {samplers.length > 0 ? (
                      samplers.map((sampler) => (
                        <option key={sampler.name} value={sampler.name}>
                          {sampler.name.toUpperCase()} - {sampler.description}
                        </option>
                      ))
                    ) : (
                      <option value="euler_a">Loading...</option>
                    )}
                  </select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="scheduler">Scheduler</Label>
                  <select
                    id="scheduler"
                    name="scheduler"
                    value={formData.scheduler}
                    onChange={handleInputChange}
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  >
                    {schedulers.length > 0 ? (
                      schedulers.map((scheduler) => (
                        <option key={scheduler.name} value={scheduler.name}>
                          {scheduler.name.toUpperCase()} - {scheduler.description}
                        </option>
                      ))
                    ) : (
                      <option value="default">Loading...</option>
                    )}
                  </select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="vae">VAE (optional)</Label>
                  <select
                    id="vae"
                    value={selectedVae}
                    onChange={(e) => setSelectedVae(e.target.value)}
                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
                  >
                    <option value="">Default VAE</option>
                    {vaeModels.map((vae) => (
                      <option key={vae.id} value={vae.name}>
                        {vae.name}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="batch_count">Batch Count</Label>
                  <Input
                    id="batch_count"
                    name="batch_count"
                    type="number"
                    value={formData.batch_count}
                    onChange={handleInputChange}
                    min={1}
                    max={4}
                  />
                </div>

                <div className="flex gap-2">
                  <Button type="submit" disabled={loading} className="flex-1">
                    {loading ? (
                      <>
                        <Loader2 className="h-4 w-4 animate-spin" />
                        Generating...
                      </>
                    ) : (
                      'Generate'
                    )}
                  </Button>
                  {loading && (
                    <Button type="button" variant="destructive" onClick={handleCancel}>
                      <X className="h-4 w-4" />
                      Cancel
                    </Button>
                  )}
                </div>

                {error && (
                  <div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
                    {error}
                  </div>
                )}

                {loading && jobInfo && (
                  <div className="rounded-md bg-muted p-3 text-sm">
                    <p>Job ID: {jobInfo.id || jobInfo.request_id || 'N/A'}</p>
                    <p>Status: {jobInfo.status}</p>
                    {jobInfo.progress !== undefined && (
                      <p>Progress: {Math.round(jobInfo.progress * 100)}%</p>
                    )}
                  </div>
                )}
              </form>
            </CardContent>
          </Card>

          {/* Right Panel - Generated Images */}
          <Card>
            <CardContent className="pt-6">
              <div className="space-y-4">
                <h3 className="text-lg font-semibold">Generated Images</h3>
                {generatedImages.length === 0 ? (
                  <div className="flex h-96 items-center justify-center rounded-lg border-2 border-dashed border-border">
                    <p className="text-muted-foreground">
                      {loading ? 'Generating...' : 'Generated images will appear here'}
                    </p>
                  </div>
                ) : (
                  <div className="grid gap-4">
                    {generatedImages.map((image, index) => (
                      <div key={index} className="relative group">
                        <img
                          src={image}
                          alt={`Generated ${index + 1}`}
                          className="w-full rounded-lg border border-border"
                        />
                        <Button
                          size="icon"
                          variant="secondary"
                          className="absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity"
                          onClick={() => downloadImage(image, `generated-${Date.now()}-${index}.png`)}
                        >
                          <Download className="h-4 w-4" />
                        </Button>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </MainLayout>
  );
}
