'use client';

import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useAuthStore } from '@/lib/auth-store';
import { API_BASE_URL } from '@/lib/constants';
import { useLanguage } from '@/lib/language-context';
import { Edit } from 'lucide-react';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useState } from 'react';
import AppointmentForm from './AppointmentForm';
import PaginationControls from '@/components/common/PaginationControls';

interface Appointment {
  _id: string;
  patientId: {
    _id: string;
    userId: {
      firstName: string;
      lastName: string;
      email: string;
    };
  };
  doctorId: {
    _id: string;
    userId: {
      firstName: string;
      lastName: string;
    };
    specialization: string;
  };
  appointmentDate: string;
  status: 'Scheduled' | 'Completed' | 'Cancelled';
  notes?: string;
}

type AppointmentFormState = {
  _id?: string;
  patientId?: string | { _id?: string };
  doctorId?: string | { _id?: string };
  appointmentDate?: string;
  notes?: string;
  status?: Appointment['status'];
};

export default function AppointmentCalendar() {
  const { t } = useLanguage();
  const searchParams = useSearchParams();
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterStatus, setFilterStatus] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(12);
  const [totalPages, setTotalPages] = useState(1);
  const [totalAppointments, setTotalAppointments] = useState(0);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [selectedAppointment, setSelectedAppointment] = useState<AppointmentFormState | null>(null);

  useEffect(() => {
    const shouldBook = searchParams.get('book') === 'true';
    const patientId = searchParams.get('patientId');

    if (shouldBook) {
      setSelectedAppointment(patientId ? { patientId } : null);
      setIsDialogOpen(true);
    }
  }, [searchParams]);

  const fetchAppointments = useCallback(async (page: number = 1, status: string = 'all') => {
    try {
      setLoading(true);
      const token = useAuthStore.getState().token;
      const queryParams = new URLSearchParams({
        page: page.toString(),
        limit: pageSize.toString(),
      });
      if (status !== 'all') {
        queryParams.append('status', status);
      }

      const response = await fetch(`${API_BASE_URL}/api/appointments?${queryParams.toString()}`, {
        headers: {
          'x-auth-token': token || '',
        },
      });
      const data = await response.json();
      if (data.success) {
        setAppointments(data.data);
        setTotalPages(Math.max(1, data.meta?.totalPages || 1));
        setTotalAppointments(data.meta?.total || 0);
      }
    } catch (error) {
      console.error('Error fetching appointments:', error);
    } finally {
      setLoading(false);
    }
  }, [pageSize]);

  useEffect(() => {
    fetchAppointments(currentPage, filterStatus);
  }, [currentPage, filterStatus, fetchAppointments]);

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'Scheduled':
        return 'text-blue-700 bg-blue-50 border border-blue-200 hover:bg-blue-100';
      case 'Completed':
        return 'text-green-700 bg-green-50 border border-green-200 hover:bg-green-100';
      case 'Cancelled':
        return 'text-red-700 bg-red-50 border border-red-200 hover:bg-red-100';

      default:
        return 'text-gray-700 bg-gray-50 border border-gray-200 hover:bg-gray-100';
    }
  };

  const handleStatusChange = async (id: string, newStatus: string) => {
    try {
      const token = useAuthStore.getState().token;
      const response = await fetch(`${API_BASE_URL}/api/appointments/${id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'x-auth-token': token || '',
        },
        body: JSON.stringify({ status: newStatus }),
      });

      if (response.ok) {
        setAppointments(appointments.map(apt =>
          apt._id === id ? { ...apt, status: newStatus as Appointment['status'] } : apt
        ));
      }
    } catch (error) {
      console.error('Error updating status:', error);
    }
  };



  const filteredAppointments = appointments;

  return (
    <div className="space-y-8">
      <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <h2 className="text-3xl font-bold tracking-tight">{t('appointments.title')}</h2>
          <p className="text-muted-foreground mt-1">{t('dashboard.manageSchedule')}</p>
        </div>
        <Button
          className="h-11 px-6 gap-2 bg-primary hover:bg-primary/90 text-primary-foreground shadow-lg transition-all hover:scale-105"
          onClick={() => {
            setSelectedAppointment(null);
            setIsDialogOpen(true);
          }}
        >
          {t('appointments.bookAppointment')}
        </Button>
      </div>

      <div className="flex flex-col sm:flex-row items-center gap-4 bg-muted/40 p-4 rounded-xl border">
        <span className="text-sm font-medium text-muted-foreground">{t('appointments.filterByStatusLabel')}</span>
        <div className="w-full sm:w-56">
          <Select
            value={filterStatus}
            onValueChange={(value) => {
              setCurrentPage(1);
              setFilterStatus(value);
            }}
          >
            <SelectTrigger className="h-10 bg-background border-input/60 focus:ring-primary/20">
              <SelectValue placeholder={t('appointments.filterByStatus')} />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">{t('appointments.all')}</SelectItem>
              <SelectItem value="Scheduled">{t('appointments.scheduled')}</SelectItem>
              <SelectItem value="Completed">{t('appointments.completed')}</SelectItem>
              <SelectItem value="Cancelled">{t('appointments.cancelled')}</SelectItem>

            </SelectContent>
          </Select>
        </div>
      </div>

      <PaginationControls
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={setCurrentPage}
        maxPageButtons={3}
        alignment="right"
        showSummary={false}
        showPageSize={false}
        loading={loading}
        className="border-0 px-0 py-0"
        labels={{
          showing: t('common.showing'),
          to: t('common.to'),
          of: t('common.of'),
          perPage: t('common.perPage'),
          previous: t('common.previous'),
          next: t('common.next'),
        }}
      />

      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
        {loading ? (
          <div className="col-span-full flex flex-col items-center justify-center p-12 text-center text-muted-foreground bg-muted/20 rounded-xl border border-dashed border-muted-foreground/20">
            <p>{t('common.loading')}</p>
          </div>
        ) : filteredAppointments.length === 0 ? (
          <div className="col-span-full flex flex-col items-center justify-center p-12 text-center text-muted-foreground bg-muted/20 rounded-xl border border-dashed border-muted-foreground/20">
            <p>{t('appointments.noAppointmentsFound')}</p>
          </div>
        ) : (
          filteredAppointments.map((appointment) => (
            <Card
              key={appointment._id}
              className={`group relative overflow-hidden transition-all duration-300 hover:shadow-xl hover:-translate-y-1 border-l-4 ${appointment.status === 'Scheduled' ? 'border-l-blue-500' :
                appointment.status === 'Completed' ? 'border-l-green-500' :
                  appointment.status === 'Cancelled' ? 'border-l-red-500' :
                    'border-l-gray-500'
                }`}
            >
              <CardHeader className="pb-3">
                <div className="flex flex-col lg:flex-row lg:justify-between lg:items-start gap-3 min-w-0">
                  <div className="space-y-1 min-w-0 flex-1">
                    <CardTitle className="text-lg font-semibold flex items-center gap-2">
                      {appointment.patientId?.userId ? (
                        <Link
                          href={`/patients/${appointment.patientId._id}`}
                          className="truncate text-primary hover:underline"
                          title={`${appointment.patientId.userId.firstName} ${appointment.patientId.userId.lastName}`}
                        >
                          {`${appointment.patientId.userId.firstName} ${appointment.patientId.userId.lastName}`}
                        </Link>
                      ) : (
                        <span
                          className="truncate"
                          title={t('appointments.unknownPatient')}
                        >
                          {t('appointments.unknownPatient')}
                        </span>
                      )}
                    </CardTitle>
                    <p className="text-sm text-muted-foreground flex items-center gap-1 min-w-0">
                      <span className="truncate" title={appointment.doctorId?.userId ? `${appointment.doctorId.userId.firstName} ${appointment.doctorId.userId.lastName}` : t('appointments.unknownDoctor')}>
                        {appointment.doctorId?.userId ? `${appointment.doctorId.userId.firstName} ${appointment.doctorId.userId.lastName}` : t('appointments.unknownDoctor')}
                      </span>
                    </p>
                  </div>

                  <div className="flex w-full lg:w-auto lg:flex-col items-start lg:items-end gap-2 shrink-0">
                    <Select
                      defaultValue={appointment.status}
                      onValueChange={(val) => handleStatusChange(appointment._id, val)}
                    >
                      <SelectTrigger
                        className={`h-8 w-full lg:w-auto lg:min-w-[124px] lg:max-w-[140px] text-[11px] sm:text-xs font-semibold uppercase tracking-wide border-0 shadow-sm transition-colors ${getStatusColor(appointment.status)}`}
                      >
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="Scheduled">{t('appointments.scheduled')}</SelectItem>
                        <SelectItem value="Completed">{t('appointments.completed')}</SelectItem>
                        <SelectItem value="Cancelled">{t('appointments.cancelled')}</SelectItem>

                      </SelectContent>
                    </Select>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4 pt-2">
                  <div className="flex items-center gap-3 text-sm bg-secondary/30 p-2.5 rounded-lg">
                    <div className="h-8 w-8 rounded-full bg-background flex items-center justify-center shadow-sm text-primary">
                      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="18" x="3" y="4" rx="2" ry="2" /><line x1="16" x2="16" y1="2" y2="6" /><line x1="8" x2="8" y1="2" y2="6" /><line x1="3" x2="21" y1="10" y2="10" /></svg>
                    </div>
                    <div className="flex flex-col">
                      <span className="text-xs text-muted-foreground font-medium uppercase tracking-wide">{t('appointments.dateTime')}</span>
                      <span className="font-semibold">{new Date(appointment.appointmentDate).toLocaleString()}</span>
                    </div>
                  </div>


                  {appointment.notes && (
                    <div className="bg-muted/30 p-3 rounded-lg border border-dashed border-muted-foreground/30">
                      <p className="text-xs text-muted-foreground font-medium mb-1 uppercase tracking-wider">{t('appointments.notes')}</p>
                      <p className="text-sm italic text-gray-700">{appointment.notes}</p>
                    </div>
                  )}

                  <div className="flex justify-end gap-2 pt-3 border-t mt-3 opacity-0 group-hover:opacity-100 transition-opacity">
                    <Button
                      variant="outline"
                      size="sm"
                      className="h-8 w-8 p-0 text-blue-600 hover:text-blue-700 hover:bg-blue-50"
                      onClick={() => {
                        setSelectedAppointment(appointment);
                        setIsDialogOpen(true);
                      }}
                    >
                      <Edit className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>

      <PaginationControls
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={setCurrentPage}
        maxPageButtons={3}
        loading={loading}
        pageSize={pageSize}
        pageSizeOptions={[6, 12, 24, 48]}
        onPageSizeChange={(size) => {
          setPageSize(size);
          setCurrentPage(1);
        }}
        showingFrom={totalAppointments > 0 ? (currentPage - 1) * pageSize + 1 : 0}
        showingTo={Math.min(currentPage * pageSize, totalAppointments)}
        totalItems={totalAppointments}
        labels={{
          showing: t('common.showing'),
          to: t('common.to'),
          of: t('common.of'),
          perPage: t('common.perPage'),
          previous: t('common.previous'),
          next: t('common.next'),
        }}
      />

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="w-[calc(100vw-2rem)] max-w-[calc(100vw-2rem)] p-4 sm:max-w-2xl sm:p-6 max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle className="text-xl font-bold">
              {selectedAppointment ? t('appointments.editAppointment') : t('appointments.bookAppointment')}
            </DialogTitle>
          </DialogHeader>
          <div className="pt-2">
            <AppointmentForm
              initialData={selectedAppointment ?? undefined}
              onSuccess={() => {
                setIsDialogOpen(false);
                fetchAppointments(currentPage, filterStatus);
              }}
              onCancel={() => setIsDialogOpen(false)}
            />
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
