<template>
  <div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
        
        <!-- Profile Section -->
        <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>Client Profile</span>
                <span class="text-sm text-gray-500">{{ showProfile ? 'Hide' : 'Show' }}</span>
             </h3>
             <form v-if="showProfile" @submit.prevent="updateProfile" class="mt-6 space-y-6 max-w-2xl">
                 <!-- Profile fields... (Same as before) -->
                 <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 leading-6 text-gray-900">Company Name</label>
                    <input type="text" v-model="profileForm.company_name" class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                </div>
                <div>
                    <label class="block text-sm font-medium leading-6 text-gray-900">Contact Person</label>
                    <input type="text" v-model="profileForm.contact_person" class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                </div>
                <div>
                    <button type="submit" class="rounded-md bg-indigo-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">Save Profile</button>
                </div>
            </form>
        </div>

        <!-- Post a Job Section -->
        <div class="bg-white p-6 rounded shadow">
             <h3 class="text-lg font-medium text-gray-900">Post a New Job</h3>
             <form @submit.prevent="postJob" class="mt-6 space-y-4 max-w-2xl">
                 <div class="grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-2">
                    <div>
                        <label class="block text-sm font-medium leading-6 text-gray-900">Job Title</label>
                        <input type="text" v-model="jobForm.title" required class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                    <div>
                        <label class="block text-sm font-medium leading-6 text-gray-900">Role Type</label>
                         <select v-model="jobForm.role_type" class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                            <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 leading-6 text-gray-900">Start Time</label>
                        <input type="datetime-local" v-model="jobForm.start_time" required class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                     <div>
                        <label class="block text-sm font-medium leading-6 text-gray-900">End Time</label>
                        <input type="datetime-local" v-model="jobForm.end_time" required class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                    <div>
                        <label class="block text-sm font-medium leading-6 text-gray-900">Rate (£/hr)</label>
                        <input type="number" step="0.01" v-model="jobForm.rate_per_hour" required class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                     <div>
                        <label class="block text-sm font-medium leading-6 text-gray-900">Location</label>
                        <input type="text" v-model="jobForm.location" required class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                     <div>
                        <label class="block text-sm font-medium leading-6 text-gray-900">Postcode</label>
                        <input type="text" v-model="jobForm.postcode" required class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6">
                    </div>
                 </div>
                 <div>
                    <label class="block text-sm font-medium leading-6 text-gray-900">Description / Notes</label>
                    <textarea v-model="jobForm.description" rows="3" class="mt-2 block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6"></textarea>
                 </div>
                 <div>
                     <button type="submit" class="rounded-md bg-blue-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-blue-500">Post Job</button>
                 </div>
             </form>
        </div>

        <!-- My Posted Jobs & Applications -->
         <div class="bg-white p-6 rounded shadow">
             <h3 class="text-lg font-medium text-gray-900">My Posted Jobs</h3>
             <ul role="list" class="divide-y divide-gray-100 mt-4">
                <li v-for="job in myJobs" :key="job.id" class="flex flex-col gap-4 py-5">
                     <div class="flex justify-between">
                         <div class="min-w-0 flex-auto">
                            <p class="text-sm font-semibold leading-6 text-gray-900">{{ job.title }} ({{ job.role_type }})</p>
                            <p class="mt-1 truncate text-xs leading-5 text-gray-500">{{ job.location }} - {{ new Date(job.start_time).toLocaleString() }}</p>
                         </div>
                          <div class="hidden sm:flex sm:flex-col sm:items-end">
                            <p class="text-xs text-gray-500">Status: {{ job.status }}</p>
                         </div>
                     </div>
                     
                     <!-- Bookings / Applications for this Job -->
                     <div v-if="getBookingsForJob(job.id).length > 0" class="ml-4 border-l-2 pl-4">
                         <h4 class="text-xs font-bold uppercase text-gray-500">Applications / Bookings</h4>
                         <ul class="mt-2 space-y-2">
                             <li v-for="booking in getBookingsForJob(job.id)" :key="booking.id" class="text-sm flex justify-between items-center bg-gray-50 p-2 rounded">
                                 <div>
                                     <span class="font-medium">{{ booking.worker.name }}</span> ({{ booking.worker.worker_profile?.job_role }})
                                     <span class="text-xs ml-2 px-2 py-0.5 rounded" :class="{'bg-yellow-100 text-yellow-800': booking.status === 'applied', 'bg-green-100 text-green-800': booking.status === 'approved', 'bg-blue-100 text-blue-800': booking.status === 'completed_pending_review'}">{{ booking.status }}</span>
                                 </div>
                                 <div class="flex gap-2">
                                     <button v-if="booking.status === 'applied'" @click="acceptBooking(booking.id)" class="text-green-600 hover:text-green-900 text-xs font-bold">Accept</button>
                                     <div v-if="booking.status === 'completed_pending_review'" class="text-xs">
                                         Timesheet: {{ new Date(booking.actual_start_time).toLocaleTimeString() }} - {{ new Date(booking.actual_end_time).toLocaleTimeString() }} (Break: {{ booking.break_minutes }}m)
                                         <button @click="approveTimesheet(booking.id)" class="ml-2 text-green-600 font-bold border border-green-600 px-2 py-1 rounded hover:bg-green-50">Approve Timesheet</button>
                                     </div>
                                     <div v-if="booking.status === 'completed_approved'">
                                         <button @click="initiatePayment(booking)" class="text-blue-600 font-bold border border-blue-600 px-2 py-1 rounded hover:bg-blue-50">Pay Now</button>
                                     </div>
                                     <div v-if="booking.status === 'paid'" class="text-green-600 font-bold">
                                         Paid
                                         <button v-if="!hasReviewed(booking.id)" @click="openReviewModal(booking)" class="ml-2 text-indigo-600 border border-indigo-600 px-2 py-1 rounded text-xs hover:bg-indigo-50">Rate Worker</button>
                                     </div>
                                 </div>
                             </li>
                         </ul>
                     </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 Worker</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>


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

<script setup>
import { reactive, onMounted, ref } from 'vue';
import { useAuthStore } from '../../stores/auth';
import axios from 'axios';

const authStore = useAuthStore();
const successMessage = ref('');
const showProfile = ref(false);
const myJobs = ref([]);
const bookings = ref([]);
const showReviewModal = ref(false);
const selectedBooking = ref(null);
const reviewForm = reactive({ rating: 5, comment: '' });

// ... (previous reactive state)

// ... (previous methods)

const initiatePayment = async (booking) => {
    if (!confirm('Proceed to payment?')) return;

    try {
        const response = await axios.post(`/api/bookings/${booking.id}/pay`);
        const { clientSecret, isMock, mockIntent } = response.data;

        if (isMock) {
            alert(`Mock Payment Successful! (ID: ${mockIntent.id})`);
            await axios.post(`/api/bookings/${booking.id}/confirm-payment`);
            fetchBookings();
        } else {
            alert('Live Stripe Connect integration requires frontend Stripe.js. Use Sandbox mode for now.');
        }
    } catch (e) {
        alert('Payment initialization failed');
    }
}

const hasReviewed = (bookingId) => {
    // POC: Assume not reviewed for now to allow testing
    return false; 
}

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');
    }
}


const profileForm = reactive({
    company_name: '',
    contact_person: '',
    // Add other fields as needed
});

const jobForm = reactive({
    title: '',
    role_type: 'Carer',
    start_time: '',
    end_time: '',
    rate_per_hour: '',
    location: '',
    postcode: '',
    description: ''
});

const fetchMyJobs = async () => {
    try {
        const response = await axios.get('/api/my-jobs');
        myJobs.value = response.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 getBookingsForJob = (jobId) => {
    return bookings.value.filter(b => b.job_id === jobId);
}

const acceptBooking = async (bookingId) => {
     try {
        await axios.post(`/api/bookings/${bookingId}/accept`);
        alert('Worker Accepted!');
        fetchMyJobs();
        fetchBookings();
    } catch (e) {
        alert('Failed to accept');
    }
}

const approveTimesheet = async (bookingId) => {
     try {
        await axios.post(`/api/bookings/${bookingId}/approve`);
        alert('Timesheet Approved!');
        fetchBookings();
    } catch (e) {
        alert('Failed to approve');
    }
}

const postJob = async () => {
    try {
        await axios.post('/api/jobs', jobForm);
        alert('Job Posted Successfully!');
        fetchMyJobs();
        // Reset form...
    } catch (e) {
        alert('Failed to post job. Check fields.');
    }
}

const updateProfile = async () => {
    // ... same as before
    try {
        await authStore.updateClientProfile(profileForm);
        successMessage.value = 'Profile updated';
    } catch (e) {
        alert('Failed');
    }
};

onMounted(() => {
    if (authStore.user?.client_profile) {
        Object.assign(profileForm, authStore.user.client_profile);
    }
    fetchMyJobs();
    fetchBookings();
});
</script>
