'use client';

import * as React from 'react';
import { Download, Loader2, RefreshCw, Code2, Globe, Layout, Palette } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Progress } from '@/components/ui/progress';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { FaviconFileUpload } from './FaviconFileUpload';
import { CodeSnippet } from './CodeSnippet';
import { generateFaviconSet } from '@/lib/favicon/faviconService';
import { downloadBlobsAsZip } from '@/lib/media/utils/fileUtils';
import type { FaviconSet, FaviconOptions } from '@/types/favicon';
import { toast } from 'sonner';

export function FaviconGenerator() {
  const [sourceFile, setSourceFile] = React.useState<File | null>(null);
  const [options, setOptions] = React.useState<FaviconOptions>({
    name: 'My Awesome App',
    shortName: 'App',
    backgroundColor: '#ffffff',
    themeColor: '#3b82f6',
  });
  const [isGenerating, setIsGenerating] = React.useState(false);
  const [progress, setProgress] = React.useState(0);
  const [result, setResult] = React.useState<FaviconSet | null>(null);

  const handleGenerate = async () => {
    if (!sourceFile) {
      toast.error('Please upload a source image');
      return;
    }

    setIsGenerating(true);
    setProgress(0);

    try {
      const resultSet = await generateFaviconSet(sourceFile, options, (p) => {
        setProgress(p);
      });
      setResult(resultSet);
      toast.success('Favicon set generated successfully!');
    } catch (error) {
      console.error(error);
      toast.error('Failed to generate favicons');
    } finally {
      setIsGenerating(false);
    }
  };

  const handleDownloadAll = async () => {
    if (!result) return;

    const files = result.icons.map((icon) => ({
      blob: icon.blob!,
      filename: icon.name,
    }));

    // Add manifest to ZIP
    const manifestBlob = new Blob([result.manifest], { type: 'application/json' });
    files.push({
      blob: manifestBlob,
      filename: 'site.webmanifest',
    });

    await downloadBlobsAsZip(files, 'favicons.zip');
    toast.success('Downloading favicons ZIP...');
  };

  const handleReset = () => {
    setSourceFile(null);
    setResult(null);
    setProgress(0);
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
      {/* Settings Column */}
      <div className="lg:col-span-4 space-y-6">
        <Card className="glass">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Layout className="h-5 w-5 text-primary" />
              App Details
            </CardTitle>
            <CardDescription>
              Configure how your app appears on devices
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="app-name">Application Name</Label>
              <Input
                id="app-name"
                value={options.name}
                onChange={(e) => setOptions({ ...options, name: e.target.value })}
                placeholder="e.g. My Awesome Website"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="short-name">Short Name</Label>
              <Input
                id="short-name"
                value={options.shortName}
                onChange={(e) => setOptions({ ...options, shortName: e.target.value })}
                placeholder="e.g. My App"
              />
              <p className="text-[10px] text-muted-foreground">Used for mobile home screen labels</p>
            </div>
          </CardContent>
        </Card>

        <Card className="glass">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Palette className="h-5 w-5 text-primary" />
              Theme Colors
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div className="space-y-2">
                <Label htmlFor="bg-color">Background</Label>
                <div className="flex gap-2">
                  <Input
                    id="bg-color"
                    type="color"
                    className="w-10 p-1 h-10 shrink-0"
                    value={options.backgroundColor}
                    onChange={(e) => setOptions({ ...options, backgroundColor: e.target.value })}
                  />
                  <Input
                    className="font-mono text-xs"
                    value={options.backgroundColor}
                    onChange={(e) => setOptions({ ...options, backgroundColor: e.target.value })}
                  />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="theme-color">Theme</Label>
                <div className="flex gap-2">
                  <Input
                    id="theme-color"
                    type="color"
                    className="w-10 p-1 h-10 shrink-0"
                    value={options.themeColor}
                    onChange={(e) => setOptions({ ...options, themeColor: e.target.value })}
                  />
                  <Input
                    className="font-mono text-xs"
                    value={options.themeColor}
                    onChange={(e) => setOptions({ ...options, themeColor: e.target.value })}
                  />
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="glass overflow-hidden">
          <CardContent className="p-6">
            <FaviconFileUpload
              selectedFile={sourceFile}
              onFileSelect={setSourceFile}
              onFileRemove={() => setSourceFile(null)}
              disabled={isGenerating}
            />
            <Button
              className="w-full mt-6"
              size="lg"
              disabled={!sourceFile || isGenerating}
              onClick={handleGenerate}
            >
              {isGenerating ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Generating... {progress}%
                </>
              ) : (
                <>
                  <RefreshCw className="mr-2 h-4 w-4" />
                  Generate Favicons
                </>
              )}
            </Button>
            {result && (
              <Button
                variant="outline"
                className="w-full mt-2"
                onClick={handleReset}
              >
                Reset
              </Button>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Results Column */}
      <div className="lg:col-span-8 space-y-6">
        {!result && !isGenerating ? (
          <Card className="glass h-full flex flex-col items-center justify-center p-12 text-center text-muted-foreground border-dashed border-2">
            <Globe className="h-12 w-12 mb-4 opacity-20" />
            <h3 className="text-lg font-semibold text-foreground">Ready to generate</h3>
            <p className="max-w-xs text-sm">Upload a square image (PNG or SVG recommended) and configure your app details to get started.</p>
          </Card>
        ) : isGenerating ? (
          <Card className="glass h-full flex flex-col items-center justify-center p-12 space-y-6">
            <div className="relative">
              <div className="h-24 w-24 rounded-full border-4 border-primary/20 animate-pulse" />
              <Loader2 className="h-12 w-12 text-primary animate-spin absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2" />
            </div>
            <div className="w-full max-w-sm space-y-2">
              <div className="flex justify-between text-xs font-bold uppercase tracking-widest text-muted-foreground">
                <span>Processing Icons</span>
                <span>{progress}%</span>
              </div>
              <Progress value={progress} className="h-1.5" />
            </div>
          </Card>
        ) : (
          <div className="space-y-6 animate-fadeIn">
            <div className="flex items-center justify-between gap-4">
              <h2 className="text-2xl font-bold tracking-tight">Generated Assets</h2>
              <Button onClick={handleDownloadAll} variant="default" className="shadow-lg shadow-primary/20">
                <Download className="mr-2 h-4 w-4" />
                Download All (ZIP)
              </Button>
            </div>

            <Tabs defaultValue="icons" className="w-full">
              <TabsList className="w-full">
                <TabsTrigger value="icons" className="flex items-center gap-2">
                  <Layout className="h-4 w-4" />
                  Icons
                </TabsTrigger>
                <TabsTrigger value="html" className="flex items-center gap-2">
                  <Code2 className="h-4 w-4" />
                  HTML Code
                </TabsTrigger>
                <TabsTrigger value="manifest" className="flex items-center gap-2">
                  <Globe className="h-4 w-4" />
                  Manifest
                </TabsTrigger>
              </TabsList>

              <TabsContent value="icons" className="mt-6">
                <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                  {result?.icons.map((icon) => (
                    <Card key={icon.name} className="glass group overflow-hidden">
                      <div className="p-4 flex flex-col items-center text-center space-y-3">
                        <div className="relative h-20 w-20 flex items-center justify-center bg-black/20 rounded-lg p-2 border border-border group-hover:scale-110 transition-transform duration-300">
                          {icon.previewUrl && (
                            <img
                              src={icon.previewUrl}
                              alt={icon.name}
                              className="max-w-full max-h-full object-contain"
                            />
                          )}
                        </div>
                        <div className="space-y-1 w-full">
                          <p className="text-[10px] font-bold text-foreground truncate uppercase tracking-tighter" title={icon.name}>
                            {icon.name}
                          </p>
                          <p className="text-[10px] text-muted-foreground">
                            {icon.width}x{icon.height} • {(icon.size / 1024).toFixed(1)} KB
                          </p>
                        </div>
                      </div>
                    </Card>
                  ))}
                </div>
              </TabsContent>

              <TabsContent value="html" className="mt-6 space-y-4">
                <div className="space-y-2">
                  <Label>Embed in your &lt;head&gt;</Label>
                  {result && <CodeSnippet code={result.htmlCode} />}
                </div>
                <div className="p-4 rounded-lg bg-info/5 border border-info/20">
                  <p className="text-xs text-info leading-relaxed">
                    <strong>Note:</strong> Make sure to place the generated files in your website&apos;s root directory or update the <code>href</code> paths accordingly.
                  </p>
                </div>
              </TabsContent>

              <TabsContent value="manifest" className="mt-6">
                <div className="space-y-2">
                  <Label>site.webmanifest</Label>
                  {result && <CodeSnippet code={result.manifest} />}
                </div>
              </TabsContent>
            </Tabs>
          </div>
        )}
      </div>
    </div>
  );
}
