import { useState, useRef } from 'react';
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Label } from "./ui/label";
import { X } from "lucide-react";
import PocketBase from 'pocketbase';

const pb = new PocketBase('https://tst-pb.s38.siliconpin.com');
const INVOICE_API_URL = 'https://host-api.cs1.hz.siliconpin.com/v1/users/';

export function AvatarUpload({ userId }: { userId: string }) {
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      setSelectedFile(e.target.files[0]);
    }
  };

  const handleRemoveFile = () => {
    setSelectedFile(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleUpload = async () => {
    if (!selectedFile || !userId) return;
    
    setIsUploading(true);
    
    try {
      // 1. Upload to PocketBase
      const formData = new FormData();
      formData.append('avatar', selectedFile);
      
      // Update PocketBase user record
      const pbRecord = await pb.collection('users').update(userId, formData);
      
      // Get the avatar URL from PocketBase
      const avatarUrl = pb.getFileUrl(pbRecord, pbRecord.avatar, {
        thumb: '100x100'
      });
      
      // 2. Update PHP backend session
      const response = await fetch(`${INVOICE_API_URL}?query=login`, {
        method: 'POST',
        credentials: 'include', // Important for sessions to work
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          avatar: avatarUrl,
          query: 'avatar_update'
        })
      });
      
      if (!response.ok) {
        throw new Error('Failed to update session');
      }
      
      // Success - you might want to refresh the user data or show a success message
      window.location.reload();
      
    } catch (error) {
      console.error('Error uploading avatar:', error);
      alert('Failed to update avatar');
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div className="space-y-4">
      {!selectedFile ? (
        <div className="space-y-2">
          <div className="flex items-center gap-4">
            <Label 
              htmlFor="avatar" 
              className="bg-primary hover:bg-primary/90 text-primary-foreground py-2 px-4 text-sm rounded-md cursor-pointer transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
              Change Avatar
            </Label>
            <Input 
              type="file" 
              id="avatar" 
              ref={fileInputRef} 
              accept="image/jpeg,image/png,image/gif" 
              className="hidden" 
              onChange={handleFileChange}
            />
            <Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
              Browse
            </Button>
          </div>
          <p className="text-xs text-muted-foreground">
            JPG, GIF or PNG. 1MB max.
          </p>
        </div>
      ) : (
        <div className="flex items-center justify-between p-3 space-x-2">
          <div className="truncate max-w-[200px]">
            <p className="text-sm font-medium truncate">{selectedFile.name}</p>
            <p className="text-xs text-muted-foreground">{(selectedFile.size / 1024).toFixed(2)} KB</p>
          </div>
          <Button 
            size="sm" 
            className="text-xs p-1 h-fit"
            onClick={handleUpload}
            disabled={isUploading}
          >
            {isUploading ? 'Uploading...' : 'Update'}
          </Button>
          <Button 
            size="sm" 
            onClick={handleRemoveFile} 
            className="bg-red-500 hover:bg-red-600 text-xs p-1 h-fit"
            disabled={isUploading}
          >
            Remove
          </Button>
        </div>
      )}
    </div>
  );
}