'use client';

import { use, useState, useEffect } from 'react';
import { Shield, Download, Lock, File, Folder, Loader2 } from 'lucide-react';
import api from '@/lib/api';

export default function PublicSharePage({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params);
  const id = resolvedParams.id;
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [requirePassword, setRequirePassword] = useState(false);
  const [password, setPassword] = useState('');
  const [fileInfo, setFileInfo] = useState<{ name: string; size: number; is_dir: boolean } | null>(null);

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

  async function fetchShareInfo(pwd?: string) {
    setLoading(true);
    setError(null);
    try {
      const data = await api.getPublicShare(id, pwd);
      if (data.require_password) {
        setRequirePassword(true);
      } else {
        setRequirePassword(false);
        setFileInfo(data);
      }
    } catch (err: any) {
      if (err.require_password) {
        setRequirePassword(true);
      } else {
        setError(err.error || 'Failed to load share');
      }
    } finally {
      setLoading(false);
    }
  }

  function handlePasswordSubmit(e: React.FormEvent) {
    e.preventDefault();
    fetchShareInfo(password);
  }

  function handleDownload() {
    const url = api.getPublicDownloadUrl(id, password);
    window.location.href = url;
  }

  function formatSize(bytes: number): string {
    if (bytes === 0) return '0 B';
    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return `${(bytes / Math.pow(1024, i)).toFixed(1)} ${units[i]}`;
  }

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
        <Loader2 className="w-8 h-8 animate-spin" style={{ color: 'var(--color-text-tertiary)' }} />
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
        <div className="max-w-md w-full p-8 rounded-2xl text-center shadow-xl" style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
          <Shield className="w-12 h-12 mx-auto mb-4" style={{ color: 'var(--color-danger)' }} />
          <h1 className="text-2xl font-bold mb-2" style={{ color: 'var(--color-text-primary)' }}>Access Denied</h1>
          <p style={{ color: 'var(--color-text-secondary)' }}>{error}</p>
        </div>
      </div>
    );
  }

  if (requirePassword) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
        <div className="max-w-md w-full p-8 rounded-2xl shadow-xl" style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
          <div className="text-center mb-8">
            <div className="w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4" style={{ backgroundColor: 'var(--color-accent-subtle)' }}>
              <Lock className="w-8 h-8" style={{ color: 'var(--color-accent)' }} />
            </div>
            <h1 className="text-2xl font-bold mb-2" style={{ color: 'var(--color-text-primary)' }}>Protected File</h1>
            <p className="text-sm" style={{ color: 'var(--color-text-secondary)' }}>This shared file is password protected.</p>
          </div>

          <form onSubmit={handlePasswordSubmit} className="space-y-4">
            <div>
              <input
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="Enter password"
                className="w-full px-4 py-3 rounded-xl outline-none"
                style={{ backgroundColor: 'var(--color-bg-tertiary)', border: '1px solid var(--color-border)', color: 'var(--color-text-primary)' }}
                autoFocus
              />
            </div>
            <button
              type="submit"
              className="w-full py-3 rounded-xl text-white font-medium transition-opacity hover:opacity-90 shadow-lg"
              style={{ background: 'linear-gradient(135deg, var(--color-accent), #8b5cf6)' }}
            >
              Unlock
            </button>
          </form>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-4" style={{ backgroundColor: 'var(--color-bg-primary)' }}>
      <div className="max-w-md w-full p-8 rounded-2xl text-center shadow-xl" style={{ backgroundColor: 'var(--color-bg-elevated)', border: '1px solid var(--color-border)' }}>
        <div className="mb-6 flex justify-center">
          {fileInfo?.is_dir ? (
            <div className="w-24 h-24 rounded-2xl flex items-center justify-center" style={{ backgroundColor: 'var(--color-accent-subtle)' }}>
              <Folder className="w-12 h-12" style={{ color: 'var(--color-accent)' }} />
            </div>
          ) : (
            <div className="w-24 h-24 rounded-2xl flex items-center justify-center" style={{ backgroundColor: 'var(--color-accent-subtle)' }}>
              <File className="w-12 h-12" style={{ color: 'var(--color-accent)' }} />
            </div>
          )}
        </div>

        <h1 className="text-xl font-bold mb-1 truncate px-4" style={{ color: 'var(--color-text-primary)' }} title={fileInfo?.name}>
          {fileInfo?.name}
        </h1>
        <p className="text-sm mb-8" style={{ color: 'var(--color-text-secondary)' }}>
          {fileInfo?.is_dir ? 'Folder' : formatSize(fileInfo?.size || 0)}
        </p>

        <button
          onClick={handleDownload}
          className="w-full flex items-center justify-center gap-2 py-3.5 rounded-xl text-white font-medium transition-opacity hover:opacity-90 shadow-lg"
          style={{ background: 'linear-gradient(135deg, var(--color-accent), #8b5cf6)' }}
        >
          <Download className="w-5 h-5" />
          Download
        </button>
      </div>
    </div>
  );
}
