import React, { useState, useEffect, useCallback } from 'react';
import { Cloud, CheckCircle, Lock, FileText, AlertCircle } from 'lucide-react';
import { formatBytes } from '../lib/utils';
import * as api from '../lib/api';

export default function SharePage({ token }) {
  const [fileInfo, setFileInfo] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);
  const [password, setPassword] = useState('');
  const [downloaded, setDownloaded] = useState(false);
  const [downloading, setDownloading] = useState(false);

  const doDownload = useCallback(async (pwd) => {
    if (!fileInfo || downloading) return;
    setDownloading(true);
    setError(null);
    try {
      const url = api.downloadSharedFile(token, pwd || null);
      const res = await fetch(url, { method: 'POST' });
      if (!res.ok) {
        const data = await res.json();
        throw new Error(data.detail || 'Download failed');
      }
      const blob = await res.blob();
      const blobUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = blobUrl;
      a.download = fileInfo.name;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(blobUrl);
      setDownloaded(true);
    } catch (err) {
      setError(err.message);
      setDownloading(false);
    }
  }, [fileInfo, downloading, token]);

  useEffect(() => {
    async function load() {
      try {
        const res = await api.getSharedFileInfo(token);
        setFileInfo(res.data);
      } catch (err) {
        const status = err.response?.status;
        if (status === 410) {
          setError('This share link has expired.');
        } else if (status === 404) {
          setError('Share link not found.');
        } else {
          setError('Failed to load shared file.');
        }
      } finally {
        setLoading(false);
      }
    }
    load();
  }, [token]);

  // Auto-download if no password required
  useEffect(() => {
    if (fileInfo && !fileInfo.requires_password && !downloaded && !downloading) {
      doDownload(null);
    }
  }, [fileInfo, downloaded, downloading, doDownload]);

  if (loading) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center">
        <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full"></div>
      </div>
    );
  }

  if (error && !fileInfo) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <div className="bg-card border border-border rounded-lg shadow-lg p-8 max-w-md w-full text-center">
          <AlertCircle className="w-12 h-12 text-destructive mx-auto mb-4" />
          <h2 className="text-xl font-semibold mb-2">Unavailable</h2>
          <p className="text-muted-foreground">{error}</p>
        </div>
      </div>
    );
  }

  // Downloaded state
  if (downloaded) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <div className="bg-card border border-border rounded-lg shadow-lg p-8 max-w-md w-full text-center">
          <div className="flex items-center justify-center gap-2 mb-6">
            <Cloud className="w-6 h-6 text-primary" />
            <span className="text-lg font-semibold">CloudSync</span>
          </div>
          <CheckCircle className="w-16 h-16 text-green-500 mx-auto mb-4" />
          <h2 className="text-xl font-semibold mb-2">File Downloaded</h2>
          <div className="flex items-center gap-3 justify-center p-3 bg-accent/50 rounded-lg mt-4">
            <FileText className="w-6 h-6 text-muted-foreground flex-shrink-0" />
            <div className="text-left min-w-0">
              <p className="font-medium text-sm truncate">{fileInfo.name}</p>
              <p className="text-xs text-muted-foreground">{formatBytes(fileInfo.size)}</p>
            </div>
          </div>
          <p className="text-sm text-muted-foreground mt-4">This link has been used and is no longer active.</p>
        </div>
      </div>
    );
  }

  // Password required state
  if (fileInfo.requires_password && !downloaded) {
    return (
      <div className="min-h-screen bg-background flex items-center justify-center p-4">
        <div className="bg-card border border-border rounded-lg shadow-lg p-8 max-w-md w-full">
          <div className="flex items-center gap-2 mb-6">
            <Cloud className="w-6 h-6 text-primary" />
            <span className="text-lg font-semibold">CloudSync</span>
          </div>

          <div className="flex items-center gap-4 mb-6 p-4 bg-accent/50 rounded-lg">
            <FileText className="w-10 h-10 text-muted-foreground flex-shrink-0" />
            <div className="min-w-0">
              <p className="font-medium truncate">{fileInfo.name}</p>
              <p className="text-sm text-muted-foreground">{formatBytes(fileInfo.size)}</p>
            </div>
          </div>

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

          <div className="mb-4">
            <label className="block text-sm font-medium mb-2">
              <Lock className="w-4 h-4 inline mr-1" />
              This file is password protected
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => { setPassword(e.target.value); setError(null); }}
              onKeyDown={(e) => { if (e.key === 'Enter' && password) doDownload(password); }}
              placeholder="Enter password"
              className="w-full h-10 px-4 bg-background border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring"
              autoFocus
            />
          </div>

          <button
            onClick={() => doDownload(password)}
            disabled={downloading || !password}
            className="w-full h-10 bg-primary text-primary-foreground rounded-lg hover:opacity-90 flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {downloading ? (
              <div className="animate-spin w-4 h-4 border-2 border-primary-foreground border-t-transparent rounded-full"></div>
            ) : (
              'Download'
            )}
          </button>
        </div>
      </div>
    );
  }

  // Downloading state (auto-download in progress, no password)
  return (
    <div className="min-h-screen bg-background flex items-center justify-center p-4">
      <div className="bg-card border border-border rounded-lg shadow-lg p-8 max-w-md w-full text-center">
        <div className="flex items-center justify-center gap-2 mb-6">
          <Cloud className="w-6 h-6 text-primary" />
          <span className="text-lg font-semibold">CloudSync</span>
        </div>
        <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full mx-auto mb-4"></div>
        <p className="text-muted-foreground">Downloading {fileInfo.name}...</p>
      </div>
    </div>
  );
}
