﻿'use client';
import { useState } from 'react';
import { Button, Descriptions, Space, Tag } from 'antd';
import type { TableColumnType } from 'antd';
import { Eye, Clock, X } from 'lucide-react';
import { DataTable } from '@/components/ui/tables/DataTable';
import { TableToolbar } from '@/components/ui/tables/TableToolbar';
import { TableActions } from '@/components/ui/tables/TableActions';
import { StatusTag } from '@/components/ui/tags/StatusTag';
import { AppDrawer } from '@/components/ui/drawers/AppDrawer';
import { AppPopconfirm } from '@/components/ui/AppPopconfirm';
import { RescheduleModal } from './RescheduleModal';
import type { Interview } from '@/types/common.types';
import type { RescheduleFormData } from './interview.schema';
import type { TableFilter } from '@/types/api.types';
import dayjs from 'dayjs';

const FILTERS: TableFilter[] = [
  {
    key: 'status',
    label: 'Status',
    options: [
      { label: 'Scheduled', value: 'scheduled' },
      { label: 'Completed', value: 'completed' },
      { label: 'Cancelled', value: 'cancelled' },
      { label: 'No Show', value: 'no_show' },
    ],
  },
  {
    key: 'interview_type',
    label: 'Type',
    options: [
      { label: 'In-Person', value: 'in_person' },
      { label: 'Phone', value: 'phone' },
      { label: 'Video', value: 'video' },
    ],
  },
];

const TYPE_COLORS: Record<string, string> = { in_person: 'blue', phone: 'cyan', video: 'purple' };

interface InterviewTableProps {
  data: Interview[];
  pagination?: Parameters<typeof DataTable>[0]['pagination'];
  loading?: boolean;
  activeFilters: Record<string, string>;
  onPageChange: (page: number, size: number) => void;
  onFilterChange: (key: string, value: string) => void;
  onRefresh: () => void;
  onReschedule: (id: string, data: RescheduleFormData) => void;
  onCancel: (id: string) => void;
  isRescheduling?: boolean;
  isCancelling?: boolean;
}

export function InterviewTable({
  data, pagination, loading, activeFilters,
  onPageChange, onFilterChange, onRefresh,
  onReschedule, onCancel, isRescheduling, isCancelling,
}: InterviewTableProps) {
  const [viewInterview, setViewInterview] = useState<Interview | null>(null);
  const [rescheduleId, setRescheduleId] = useState<string | null>(null);

  const columns: TableColumnType<Interview>[] = [
    {
      title: 'Candidate',
      key: 'candidate',
      render: (_, r) => (
        <div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>{r.first_name} {r.last_name}</div>
          <div style={{ fontSize: 11, color: '#94a3b8' }}>{r.phone}</div>
        </div>
      ),
    },
    {
      title: 'Job',
      key: 'job',
      render: (_, r) => (
        <div>
          <div style={{ fontSize: 12, fontWeight: 500 }}>{r.job_title}</div>
          <div style={{ fontSize: 11, color: '#94a3b8' }}>{r.company_name}</div>
        </div>
      ),
    },
    {
      title: 'Type',
      dataIndex: 'interview_type',
      key: 'type',
      render: (v: string) => (
        <Tag color={TYPE_COLORS[v] ?? 'default'} style={{ fontSize: 11 }}>
          {v?.replace(/_/g, ' ').toUpperCase()}
        </Tag>
      ),
    },
    {
      title: 'Scheduled',
      dataIndex: 'scheduled_at',
      key: 'scheduled',
      render: (v: string) => (
        <div>
          <div style={{ fontSize: 12, fontWeight: 500 }}>{dayjs(v).format('DD MMM YYYY')}</div>
          <div style={{ fontSize: 11, color: '#64748b' }}>{dayjs(v).format('HH:mm')}</div>
        </div>
      ),
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
      render: (v: string) => <StatusTag status={v} />,
    },
    {
      title: '',
      key: 'actions',
      width: 72,
      render: (_, r) => (
        <Space size={2}>
          <TableActions
            items={[
              { key: 'view', icon: <Eye size={14} />, label: 'View Details', onClick: () => setViewInterview(r) },
              r.status === 'scheduled'
                ? { key: 'reschedule', icon: <Clock size={14} />, label: 'Reschedule', onClick: () => setRescheduleId(r.id) }
                : null,
            ].filter(Boolean) as never[]}
          />
          {r.status === 'scheduled' && (
            <AppPopconfirm
              title="Cancel Interview"
              description={`Cancel the interview scheduled on ${dayjs(r.scheduled_at).format('DD MMM YYYY, HH:mm')}?`}
              onConfirm={() => onCancel(r.id)}
              loading={isCancelling}
              danger
              okText="Cancel Interview"
            >
              <Button type="text" size="small" danger icon={<X size={13} />} />
            </AppPopconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <>
      <div className="data-table-card">
        <TableToolbar
          title="All Interviews"
          totalCount={pagination?.total}
          filters={FILTERS}
          activeFilters={activeFilters}
          onFilterChange={onFilterChange}
          onRefresh={onRefresh}
          showDateFilter
          onDateChange={(s, e) => {
            onFilterChange('startDate', s);
            onFilterChange('endDate', e);
          }}
        />
        <DataTable<Interview>
          columns={columns}
          data={data}
          loading={loading}
          pagination={pagination}
          onPageChange={onPageChange}
          scroll={{ x: 900 }}
        />
      </div>

      <AppDrawer
        title="Interview Details"
        open={!!viewInterview}
        onClose={() => setViewInterview(null)}
        width={460}
      >
        {viewInterview && (
          <div style={{ fontSize: 13 }}>
            <StatusTag status={viewInterview.status} />
            <Descriptions column={1} size="small" bordered style={{ marginTop: 16 }}>
              <Descriptions.Item label="Candidate">{viewInterview.first_name} {viewInterview.last_name}</Descriptions.Item>
              <Descriptions.Item label="Phone">{viewInterview.phone}</Descriptions.Item>
              <Descriptions.Item label="Job">{viewInterview.job_title}</Descriptions.Item>
              <Descriptions.Item label="Company">{viewInterview.company_name}</Descriptions.Item>
              <Descriptions.Item label="Type">
                <Tag color={TYPE_COLORS[viewInterview.interview_type] ?? 'default'}>
                  {viewInterview.interview_type?.replace(/_/g, ' ').toUpperCase()}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="Scheduled At">
                {dayjs(viewInterview.scheduled_at).format('DD MMM YYYY, HH:mm')}
              </Descriptions.Item>
              {viewInterview.location && (
                <Descriptions.Item label="Location">{viewInterview.location}</Descriptions.Item>
              )}
              {viewInterview.meeting_link && (
                <Descriptions.Item label="Meeting Link">
                  <a href={viewInterview.meeting_link} target="_blank" rel="noreferrer">{viewInterview.meeting_link}</a>
                </Descriptions.Item>
              )}
              {viewInterview.interviewer_name && (
                <Descriptions.Item label="Interviewer">{viewInterview.interviewer_name}</Descriptions.Item>
              )}
              {viewInterview.notes && (
                <Descriptions.Item label="Notes">{viewInterview.notes}</Descriptions.Item>
              )}
            </Descriptions>
          </div>
        )}
      </AppDrawer>

      <RescheduleModal
        open={!!rescheduleId}
        interviewId={rescheduleId}
        loading={isRescheduling}
        onClose={() => setRescheduleId(null)}
        onSubmit={onReschedule}
      />

    </>
  );
}
