'use client';

import { useCallback, useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { ImagePlus, Loader2, Trash2, ExternalLink } from 'lucide-react';
import { DashboardLayout } from '@/components/layout/DashboardLayout';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { api, getUploadUrl, uploadForm } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { MAX_WORKER_PORTFOLIO_IMAGES } from '@ehandyhire/shared';
import { WorkerPortalShell } from '@/components/worker/WorkerPortal';
import { PortfolioCarousel } from '@/components/workers/PortfolioCarousel';
import { cn } from '@/lib/utils';

interface PortfolioImage {
  id: string;
  url: string;
  title?: string | null;
}

export default function WorkerPortfolioPage() {
  const { user } = useAuth();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [images, setImages] = useState<PortfolioImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [error, setError] = useState('');

  const workerProfileId = (user?.workerProfile as { id?: string } | undefined)?.id;

  const fetchImages = useCallback(async () => {
    try {
      const res = await api<{ data: PortfolioImage[] }>('/users/worker/portfolio');
      setImages(res.data);
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchImages();
  }, [fetchImages]);

  const handleUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    e.target.value = '';
    if (!file) return;

    if (!file.type.startsWith('image/')) {
      setError('Please select an image file');
      return;
    }

    if (images.length >= MAX_WORKER_PORTFOLIO_IMAGES) {
      setError(`Maximum ${MAX_WORKER_PORTFOLIO_IMAGES} photos allowed`);
      return;
    }

    setError('');
    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('image', file);
      await uploadForm('/users/worker/portfolio', formData);
      await fetchImages();
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Upload failed');
    } finally {
      setUploading(false);
    }
  };

  const handleDelete = async (id: string) => {
    setError('');
    setDeletingId(id);
    try {
      await api(`/users/worker/portfolio/${id}`, { method: 'DELETE' });
      setImages((prev) => prev.filter((img) => img.id !== id));
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Failed to remove photo');
    } finally {
      setDeletingId(null);
    }
  };

  const canAddMore = images.length < MAX_WORKER_PORTFOLIO_IMAGES;

  return (
    <DashboardLayout role="worker" title="Portfolio">
      <WorkerPortalShell>
        <Card>
          <CardContent className="p-6 space-y-4">
            <div className="flex items-start justify-between gap-4">
              <div>
                <h2 className="text-lg font-bold text-slate-900">Project photos</h2>
                <p className="text-sm text-muted mt-1">
                  Showcase your best work on your public profile. Add up to{' '}
                  {MAX_WORKER_PORTFOLIO_IMAGES} photos.
                </p>
              </div>
              {workerProfileId && (
                <Link
                  href={`/workers/${workerProfileId}#portfolio`}
                  className="shrink-0 text-sm text-primary font-medium hover:text-primary-dark flex items-center gap-1"
                >
                  Preview on profile
                  <ExternalLink className="h-3.5 w-3.5" />
                </Link>
              )}
            </div>

            <p className="text-sm font-medium text-slate-700">
              {images.length} / {MAX_WORKER_PORTFOLIO_IMAGES} photos
            </p>

            {loading ? (
              <div className="flex items-center justify-center py-12 text-muted">
                <Loader2 className="h-6 w-6 animate-spin" />
              </div>
            ) : images.length > 0 ? (
              <PortfolioCarousel
                images={images}
                getImageUrl={getUploadUrl}
                renderOverlay={(img) => (
                  <button
                    type="button"
                    onClick={() => handleDelete(img.id)}
                    disabled={deletingId === img.id}
                    className="absolute top-2 right-2 flex h-8 w-8 items-center justify-center rounded-full bg-black/60 text-white opacity-100 sm:opacity-0 sm:group-hover:opacity-100 transition-opacity disabled:opacity-50"
                    aria-label="Remove photo"
                  >
                    {deletingId === img.id ? (
                      <Loader2 className="h-4 w-4 animate-spin" />
                    ) : (
                      <Trash2 className="h-4 w-4" />
                    )}
                  </button>
                )}
              />
            ) : (
              <button
                type="button"
                onClick={() => fileInputRef.current?.click()}
                disabled={uploading}
                className={cn(
                  'w-full aspect-[3/1] rounded-xl border-2 border-dashed border-slate-300 bg-slate-50',
                  'flex flex-col items-center justify-center gap-2 text-muted',
                  'hover:border-primary hover:text-primary hover:bg-primary/5 transition-colors',
                  'disabled:opacity-50 disabled:pointer-events-none'
                )}
              >
                {uploading ? (
                  <Loader2 className="h-8 w-8 animate-spin" />
                ) : (
                  <>
                    <ImagePlus className="h-8 w-8" />
                    <span className="text-sm font-medium">Add your first photo</span>
                  </>
                )}
              </button>
            )}

            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleUpload}
            />

            {error && <p className="text-sm text-red-500">{error}</p>}

            {!loading && images.length === 0 && (
              <p className="text-sm text-muted text-center py-2">
                No photos yet. Add your first project photo to stand out to customers.
              </p>
            )}
          </CardContent>
        </Card>

        {canAddMore && !loading && images.length > 0 && (
          <Button
            type="button"
            variant="outline"
            className="w-full"
            disabled={uploading}
            onClick={() => fileInputRef.current?.click()}
          >
            {uploading ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin mr-2" />
                Uploading...
              </>
            ) : (
              <>
                <ImagePlus className="h-4 w-4 mr-2" />
                Add photo
              </>
            )}
          </Button>
        )}
      </WorkerPortalShell>
    </DashboardLayout>
  );
}
