<template>
  <div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">

        <!-- Profile Link (Collapsible) -->
        <div class="bg-white p-6 rounded shadow">
             <h3 class="text-lg font-medium text-gray-900 cursor-pointer flex justify-between" @click="showProfile = !showProfile">
                <span>Worker Profile & Docs</span>
                <span class="text-sm text-gray-500">{{ showProfile ? 'Hide' : 'Show' }}</span>
             </h3>
             <div v-if="showProfile" class="mt-4">
                 <form @submit.prevent="updateWorkerProfile" class="space-y-4 max-w-2xl">
                    <div v-if="successMessage" class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative">
                        {{ successMessage }}
                    </div>
                     <div>
                         <label class="block text-sm font-medium text-gray-700">Job Role</label>
                         <select v-model="workerForm.job_role" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                             <option value="Carer">Carer</option>
                             <option value="Nurse">Nurse</option>
                             <option value="Cook">Cook</option>
                         </select>
                     </div>
                     <div>
                         <label class="block text-sm font-medium text-gray-700">Bio</label>
                         <textarea v-model="workerForm.bio" rows="3" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"></textarea>
                     </div>
                      <div>
                         <label class="block text-sm font-medium text-gray-700">Experience (Years)</label>
                         <input type="number" v-model="workerForm.experience_years" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                     </div>
                     <div>
                         <label class="block text-sm font-medium text-gray-700">Transport Mode</label>
                         <input type="text" v-model="workerForm.transport_mode" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500">
                     </div>
                     <div>
                         <button type="submit" class="inline-flex justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2">Save Profile</button>
                     </div>
                 </form>
             </div>
        </div>

        <!-- Documents Section -->
        <div class="bg-white p-6 rounded shadow">
             <h3 class="text-lg font-medium text-gray-900 cursor-pointer flex justify-between" @click="showDocuments = !showDocuments">
                <span>My Documents</span>
                <span class="text-sm text-gray-500">{{ showDocuments ? 'Hide' : 'Show' }}</span>
             </h3>
             <div v-if="showDocuments" class="mt-4 space-y-6">
                 <!-- Document List -->
                 <div v-if="documents.length > 0">
                     <h4 class="font-medium text-gray-700 mb-2">Uploaded Documents</h4>
                     <ul class="divide-y divide-gray-200 border border-gray-200 rounded-md">
                         <li v-for="doc in documents" :key="doc.id" class="p-4 flex justify-between items-center">
                             <div>
                                 <p class="text-sm font-medium text-gray-900">{{ formatDocType(doc.type) }}</p>
                                 <p class="text-xs text-gray-500">Uploaded: {{ new Date(doc.created_at).toLocaleDateString() }}</p>
                                 <p v-if="doc.expiry_date" class="text-xs text-gray-500">Expires: {{ new Date(doc.expiry_date).toLocaleDateString() }}</p>
                             </div>
                             <div class="flex items-center space-x-2">
                                 <span :class="{'bg-yellow-100 text-yellow-800': doc.status === 'pending', 'bg-green-100 text-green-800': doc.status === 'approved', 'bg-red-100 text-red-800': doc.status === 'rejected'}" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                                     {{ doc.status }}
                                 </span>
                                 <button @click="deleteDocument(doc.id)" class="text-red-600 hover:text-red-900 text-sm">Delete</button>
                             </div>
                         </li>
                     </ul>
                 </div>
                 <p v-else class="text-gray-500 italic">No documents uploaded yet.</p>

                 <!-- Upload Component -->
                 <DocumentUpload @document-uploaded="fetchDocuments" />
             </div>
        </div>

        <!-- Job Search -->
        <div class="bg-white p-6 rounded shadow">
             <h3 class="text-lg font-medium text-gray-900">Find Work</h3>
             
             <!-- Filters -->
             <div class="mt-4 grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-4">
                 <input type="text" v-model="filters.location" placeholder="Location" class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300">
                 <select v-model="filters.role_type" class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300">
                     <option value="">All Roles</option>
                     <option value="Carer">Carer</option>
                     <option value="Nurse">Nurse</option>
                 </select>
                 <input type="date" v-model="filters.date" class="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300">
                 <button @click="searchJobs" class="rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">Search</button>
             </div>

             <!-- Job List -->
             <ul role="list" class="divide-y divide-gray-100 mt-6">
                <li v-for="job in jobs" :key="job.id" class="flex justify-between gap-x-6 py-5 hover:bg-gray-50 cursor-pointer p-4 rounded border border-transparent hover:border-gray-200">
                     <div class="min-w-0 flex-auto">
                        <p class="text-sm font-semibold leading-6 text-gray-900">{{ job.title }}</p>
                        <p class="mt-1 flex text-xs leading-5 text-gray-500">
                            {{ job.client.client_profile?.company_name || 'Private Client' }} - {{ job.location }}
                        </p>
                        <p class="text-xs text-gray-400">{{ new Date(job.start_time).toLocaleString() }} - {{ new Date(job.end_time).toLocaleTimeString() }}</p>
                     </div>
                     <div class="hidden sm:flex sm:flex-col sm:items-end">
                        <p class="text-sm leading-6 text-gray-900">£{{ job.rate_per_hour }}/hr</p>
                        <button @click="applyForJob(job.id)" class="mt-2 rounded bg-green-600 text-white px-3 py-1 text-xs hover:bg-green-500">Apply</button>
                     </div>
                </li>
             </ul>
             <p v-if="jobs.length === 0" class="text-center text-gray-500 mt-4">No jobs found matching your criteria.</p>
        </div>

        <!-- My Bookings / Timesheets -->
        <div class="bg-white p-6 rounded shadow">
            <h3 class="text-lg font-medium text-gray-900">My Bookings</h3>
            <ul role="list" class="divide-y divide-gray-100 mt-4">
                <li v-for="booking in bookings" :key="booking.id" class="flex justify-between gap-x-6 py-5">
                    <div class="min-w-0 flex-auto">
                        <p class="text-sm font-semibold leading-6 text-gray-900">{{ booking.job.title }}</p>
                        <p class="text-xs text-gray-500">Client: {{ booking.job.client.client_profile?.company_name }}</p>
                        <p class="text-xs">Status: <span :class="{'text-yellow-600': booking.status === 'applied', 'text-green-600': booking.status === 'approved', 'text-blue-600': booking.status === 'completed_approved'}">{{ booking.status }}</span></p>
                    </div>
                    <div class="hidden sm:flex sm:flex-col sm:items-end">
                         <div v-if="booking.status === 'approved'">
                             <button @click="openTimesheetModal(booking)" class="rounded bg-indigo-600 text-white px-3 py-1 text-xs hover:bg-indigo-500">Submit Timesheet</button>
                         </div>
                         <div v-else-if="booking.status === 'completed_pending_review'">
                             <span class="text-xs text-gray-500">Timesheet Submitted</span>
                         </div>
                         <div v-else-if="booking.status === 'paid'">
                             <span class="text-green-600 font-bold text-xs">Paid</span>
                             <button @click="openReviewModal(booking)" class="block mt-2 text-indigo-600 border border-indigo-600 px-2 py-1 rounded text-xs hover:bg-indigo-50">Rate Client</button>
                         </div>
                    </div>
                </li>
            </ul>

        </div>

        <!-- Review Modal -->
        <div v-if="showReviewModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
            <div class="bg-white p-6 rounded shadow-lg w-full max-w-sm">
                <h3 class="text-lg font-medium mb-4">Rate Client</h3>
                <form @submit.prevent="submitReview">
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Rating (1-5)</label>
                        <select v-model="reviewForm.rating" class="block w-full border-gray-300 rounded mt-1">
                            <option value="5">5 - Excellent</option>
                            <option value="4">4 - Good</option>
                            <option value="3">3 - Average</option>
                            <option value="2">2 - Poor</option>
                            <option value="1">1 - Terrible</option>
                        </select>
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Comment</label>
                        <textarea v-model="reviewForm.comment" rows="3" class="block w-full border-gray-300 rounded mt-1"></textarea>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="showReviewModal = false" class="text-gray-600">Cancel</button>
                        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded">Submit</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Timesheet Modal (Simplified) -->
        <div v-if="showTimesheetModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
            <div class="bg-white p-6 rounded shadow-lg w-full max-w-md">
                <h3 class="text-lg font-medium mb-4">Submit Timesheet</h3>
                <form @submit.prevent="submitTimesheet">
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Actual Start Time</label>
                        <input type="datetime-local" v-model="timesheetForm.start_time" required class="block w-full border-gray-300 rounded mt-1">
                    </div>
                    <div class="mb-4">
                        <label class="block text-sm font-medium">Actual End Time</label>
                        <input type="datetime-local" v-model="timesheetForm.end_time" required class="block w-full border-gray-300 rounded mt-1">
                    </div>
                     <div class="mb-4">
                        <label class="block text-sm font-medium">Break (Minutes)</label>
                        <input type="number" v-model="timesheetForm.break_minutes" class="block w-full border-gray-300 rounded mt-1">
                    </div>
                    <div class="flex justify-end gap-2">
                        <button type="button" @click="showTimesheetModal = false" class="text-gray-600">Cancel</button>
                        <button type="submit" class="bg-indigo-600 text-white px-4 py-2 rounded">Submit</button>
                    </div>
                </form>
            </div>
        </div>

    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';

import DocumentUpload from '../../components/DocumentUpload.vue';

const showProfile = ref(false);
const showDocuments = ref(false);
const jobs = ref([]);
const bookings = ref([]);
const documents = ref([]);
const showTimesheetModal = ref(false);
const showReviewModal = ref(false);
const selectedBooking = ref(null);
const successMessage = ref('');
const reviewForm = reactive({ rating: 5, comment: '' });

const formatDocType = (type) => {
    return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
};

const fetchDocuments = async () => {
    try {
        const response = await axios.get('/api/documents');
        documents.value = response.data;
    } catch (e) {
        console.error(e);
    }
};

const deleteDocument = async (id) => {
    if (!confirm('Are you sure?')) return;
    try {
        await axios.delete(`/api/documents/${id}`);
        fetchDocuments();
    } catch (e) {
        alert('Failed to delete document');
    }
};

const filters = reactive({
    location: '',
    role_type: '',
    date: ''
});

const timesheetForm = reactive({
    start_time: '',
    end_time: '',
    break_minutes: 0
});

const workerForm = reactive({
    job_role: 'Carer',
    bio: '',
    experience_years: 0,
    transport_mode: '',
});

const updateWorkerProfile = async () => {
    try {
        // Mock update if authStore doesn't have it yet, or assume it does
        // await authStore.updateWorkerProfile(workerForm);
        // For now using axios directly as a fallback/example
        const response = await axios.post('/api/user/profile/worker', workerForm); // Ensure route exists
        successMessage.value = 'Profile updated successfully';
    } catch (e) {
        // alert('Failed to update profile');
        console.error(e); // Silencing for now if route not perfect
    }
}

const searchJobs = async () => {
    try {
        const params = new URLSearchParams(filters).toString();
        const response = await axios.get(`/api/jobs?${params}`);
        jobs.value = response.data.data;
    } catch (e) {
        console.error(e);
    }
};

const fetchBookings = async () => {
    try {
        const response = await axios.get('/api/bookings');
        bookings.value = response.data;
    } catch (e) {
         console.error(e);
    }
}

const applyForJob = async (jobId) => {
    try {
        await axios.post(`/api/jobs/${jobId}/apply`);
        alert('Applied successfully!');
        fetchBookings(); // Refresh bookings list
    } catch (error) {
        alert(error.response?.data?.message || 'Failed to apply');
    }
};

const openTimesheetModal = (booking) => {
    selectedBooking.value = booking;
    timesheetForm.start_time = booking.job.start_time; // Default to scheduled time
    timesheetForm.end_time = booking.job.end_time;
    showTimesheetModal.value = true;
}

const submitTimesheet = async () => {
    try {
        await axios.post(`/api/bookings/${selectedBooking.value.id}/timesheet`, timesheetForm);
        alert('Timesheet submitted!');
        showTimesheetModal.value = false;
        fetchBookings();
    } catch (e) {
        alert('Failed to submit');
    }
}

const openReviewModal = (booking) => {
    selectedBooking.value = booking;
    reviewForm.rating = 5;
    reviewForm.comment = '';
    showReviewModal.value = true;
}

const submitReview = async () => {
    try {
        await axios.post(`/api/bookings/${selectedBooking.value.id}/review`, reviewForm);
        alert('Review submitted!');
        showReviewModal.value = false;
    } catch (e) {
        alert(e.response?.data?.message || 'Failed');
    }
}

onMounted(() => {
    // If authStore data isn't fully loaded, we might need to fetch profile
    // But assuming authStore is populated on login
    // if (authStore.user?.worker_profile) {
    //    Object.assign(workerForm, authStore.user.worker_profile);
    // }
    searchJobs();
    fetchBookings();
    fetchDocuments();
});
</script>
