'use client';

import { useState } from 'react';
import { useAuthStore } from '@/stores/authStore';
import { useRouter } from 'next/navigation';

export default function GeneralConsultationForm() {
  const router = useRouter();
  const userData = useAuthStore((state) => state.user);
  const user = userData?.profile || null;

  const [issue, setIssue] = useState('');
  const [files, setFiles] = useState([]); // Local File objects
  const [fileUrls, setFileUrls] = useState([]); // S3 URLs
  const [loading, setLoading] = useState(false);
  const [uploading, setUploading] = useState(false);

  const handleFileChange = async (e) => {
    const selectedFiles = Array.from(e.target.files || []);
    setFiles((prev) => [...prev, ...selectedFiles]);

    setUploading(true);

    try {
      const uploaded = [];

      for (const file of selectedFiles) {
        // 1. Request signed URL
        const signRes = await fetch('/api/profiles/uploads/sign-url', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            fileName: file.name,
            fileType: file.type,
            folder: 'consultation-files',
          }),
          credentials: 'include',
        });

        if (!signRes.ok) throw new Error('Failed to get signed URL');
        const { uploadUrl, fileUrl } = await signRes.json();

        // 2. Upload file to S3
        const s3Upload = await fetch(uploadUrl, {
          method: 'PUT',
          body: file,
          headers: {
            'Content-Type': file.type,
          },
        });

        if (!s3Upload.ok) throw new Error('Failed to upload file to S3');

        uploaded.push(fileUrl);
      }

      setFileUrls((prev) => [...prev, ...uploaded]);
    } catch (err) {
      console.error('File upload failed:', err);
      alert('Some files failed to upload. Please try again.');
    } finally {
      setUploading(false);
    }
  };

  const handleRemoveFile = (index) => {
    setFiles((prev) => prev.filter((_, i) => i !== index));
    setFileUrls((prev) => prev.filter((_, i) => i !== index));
  };

  const handleSubmit = async () => {
    if (!issue.trim()) return;

    setLoading(true);

    try {
      const res = await fetch('/api/consultations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          patientId: user.userId,
          doctorId: '',
          issue,
          type: 'text',
          files: fileUrls.join(','), // comma-separated S3 URLs
        }),
      });

      if (!res.ok) throw new Error('Submission failed');

      router.push('/dashboard/patient/messages');
    } catch (err) {
      console.error('Error submitting consultation:', err);
      alert('Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="bg-white p-4 rounded shadow-md mb-6">
      <h2 className="text-lg font-semibold mb-3">Post a General Consultation</h2>

      <textarea
        rows={4}
        className="w-full p-3 border border-gray-300 rounded mb-3"
        placeholder="Describe your health issue or question..."
        value={issue}
        onChange={(e) => setIssue(e.target.value)}
      />

      <label className="block bg-blue-500 text-white p-2 rounded cursor-pointer mb-2">
        Do you have pictures or documents for doctors or consultants to review? Please upload them here.
        <input
          type="file"
          multiple
          accept="image/*,application/pdf"
          className="hidden"
          onChange={handleFileChange}
        />
      </label>

      {files.length > 0 && (
        <div className="mb-3 space-y-1">
          <p className="text-sm font-semibold text-gray-600">Uploaded files:</p>
          {files.map((file, index) => (
            <div key={index} className="flex justify-between items-center text-sm bg-gray-100 p-2 rounded">
              <span>{file.name}</span>
              <button
                className="text-red-500 hover:underline ml-4"
                onClick={() => handleRemoveFile(index)}
              >
                Remove
              </button>
            </div>
          ))}
        </div>
      )}

      <button
        onClick={handleSubmit}
        disabled={loading || uploading}
        className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 disabled:opacity-50"
      >
        {loading ? 'Submitting...' : uploading ? 'Uploading...' : 'Submit'}
      </button>
    </div>
  );
}
