"use client";

import React, { useState, useEffect } from "react";
import Select from "react-select";
import toast from "react-hot-toast";
import styles from "../../commonstyle/FormStyles.module.css";
import { fetchApi } from "@/lib/api/http";
import { generateScopeSummaryPDF } from "./ScopeSummaryPDF";
import type { CompanyRow } from "@/lib/api/types/company.types";

// ─────────────────────────────────────────────────
// Types
// ─────────────────────────────────────────────────
interface SelectOption {
  value: string | number;
  label: string;
}

interface User {
  id: number;
  firstName?: string;
  lastName?: string;
  name?: string;
  email?: string;
}

interface Stage {
  stageName: string;
  auditDate: string;
  auditor: User | null;
  anzicCode?: string;
  technicalExpert?: string;
}

interface ScopeSummaryModalProps {
  isOpen: boolean;
  onClose: () => void;
  company: CompanyRow | null;
}

// ─────────────────────────────────────────────────
// Available audit stages
// ─────────────────────────────────────────────────
const AUDIT_STAGE_OPTIONS: SelectOption[] = [
  { value: "Stage 1", label: "Stage 1" },
  { value: "Stage 2", label: "Stage 2" },
  { value: "Surveillance 1", label: "Surveillance 1" },
  { value: "Surveillance 2", label: "Surveillance 2" },
  { value: "Recertification", label: "Recertification" },
];

// API base — adjust if yours is different
const USERS_API_URL =
  process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

// ─────────────────────────────────────────────────
// Component
// ─────────────────────────────────────────────────
export default function ScopeSummaryModal({
  isOpen,
  onClose,
  company,
}: ScopeSummaryModalProps) {
  // Stages state — start with 1 empty stage
  const [stages, setStages] = useState<Stage[]>([
    {
      stageName: "",
      auditDate: new Date().toISOString().split("T")[0],
      auditor: null,
    },
  ]);

  const [users, setUsers] = useState<User[]>([]);
  const [usersLoading, setUsersLoading] = useState(false);
  const [remarks, setRemarks] = useState("");
  const [generating, setGenerating] = useState(false);

  // ─── Reset state when modal opens for a new company ──
  useEffect(() => {
    if (isOpen) {
      setStages([
        {
          stageName: "",
          auditDate: new Date().toISOString().split("T")[0],
          auditor: null,
        },
      ]);
      setRemarks("");
    }
  }, [isOpen, company?.id]);

  // ─── Fetch users for auditor dropdown ──
  useEffect(() => {
    if (!isOpen) return;
    setUsersLoading(true);

    // Try common endpoints — uses whichever returns first
    fetchApi<any>(`${USERS_API_URL}/users`)
      .then((res) => {
        const list = Array.isArray(res) ? res : res?.data || [];
        setUsers(list);
      })
      .catch(() => {
        // Fallback — try /employees if /users doesn't exist
        fetchApi<any>(`${USERS_API_URL}/employees`)
          .then((res) => {
            const list = Array.isArray(res) ? res : res?.data || [];
            setUsers(list);
          })
          .catch(() => {
            toast.error("Failed to load users — check API URL");
            setUsers([]);
          });
      })
      .finally(() => setUsersLoading(false));
  }, [isOpen]);

  // ─── Build user options for react-select ──
  const userOptions: SelectOption[] = users.map((u) => ({
    value: u.id,
    label:
      u.name ||
      `${u.firstName || ""} ${u.lastName || ""}`.trim() ||
      u.email ||
      `User #${u.id}`,
  }));

  // ─── Stage row handlers ──
  const updateStage = (idx: number, patch: Partial<Stage>) => {
    setStages((prev) =>
      prev.map((s, i) => (i === idx ? { ...s, ...patch } : s)),
    );
  };

  const addStage = () => {
    setStages((prev) => [
      ...prev,
      {
        stageName: "",
        auditDate: new Date().toISOString().split("T")[0],
        auditor: null,
      },
    ]);
  };

  const removeStage = (idx: number) => {
    if (stages.length === 1) return; // keep at least 1
    setStages((prev) => prev.filter((_, i) => i !== idx));
  };

  // ─── Generate PDF ──
  const handleGenerate = () => {
    if (!company) return;

    // Validate at least one stage has both stage name and auditor
    const validStages = stages.filter((s) => s.stageName && s.auditor);
    if (validStages.length === 0) {
      toast.error("Please select at least one Audit Stage and Auditor");
      return;
    }

    setGenerating(true);

    try {
      generateScopeSummaryPDF({
        jobId: company.id,
        jobCode: company.company_code,
        clientGroup: (company as any).client_group,
        company: {
          name: company.name,
          address: company.address,
          contact_person: company.contact_person,
          designation: company.designation,
          email: company.email,
          mobile: company.mobile,
          telephone: company.telephone,
          fax: company.fax,
          certification_body: company.certification_body,
          accreditation: company.accreditation,
          scope_of_work: company.scope_of_work,
          validity: company.validity,
        },
        standards: Array.isArray(company.standards)
          ? company.standards.map((s: any) =>
              typeof s === "object" ? { name: s.name } : { name: String(s) },
            )
          : [],
        stages: validStages.map((s) => ({
          stageName: s.stageName,
          auditDate: s.auditDate,
          anzicCode: s.anzicCode || "",
          auditor: s.auditor
            ? {
                firstName: s.auditor.firstName,
                lastName: s.auditor.lastName,
              }
            : null,
          technicalExpert: s.technicalExpert || "",
        })),
        remarks,
      });

      toast.success("Scope Summary opened in new tab");
      onClose();
    } catch (err: any) {
      toast.error(err?.message || "Failed to generate report");
    } finally {
      setGenerating(false);
    }
  };

  if (!isOpen || !company) return null;

  return (
    <div className={styles.modalOverlay} onClick={onClose}>
      <div
        className={styles.modalContent}
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 720 }}
      >
        {/* ─── Header ─── */}
        <div className={styles.modalHeader}>
          <div>
            <h2 className={styles.modalTitle}>📄 Generate Scope Summary</h2>
            <p className={styles.modalSubtitle}>
              {company.name}
              {company.company_code && (
                <span style={{ color: "#9ca3af", marginLeft: 8 }}>
                  · {company.company_code}
                </span>
              )}
            </p>
          </div>
          <button className={styles.closeBtn} onClick={onClose} type="button">
            ✕
          </button>
        </div>

        {/* ─── Body ─── */}
        <div className={styles.formBody}>
          <div className={styles.sectionHeader}>
            <span className={styles.sectionDot} />
            Audit Stages & Auditors
          </div>

          <p
            style={{
              fontSize: 12,
              color: "#64748b",
              marginTop: -4,
              marginBottom: 12,
            }}
          >
            Add one or more audit stages. Each stage shows up as a row in the
            generated report.
          </p>

          {/* ─── Stages list ─── */}
          {stages.map((stage, idx) => (
            <div
              key={idx}
              style={{
                background: "#f8fafc",
                border: "1px solid #e2e8f0",
                borderRadius: 8,
                padding: 12,
                marginBottom: 10,
              }}
            >
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "center",
                  marginBottom: 10,
                }}
              >
                <span
                  style={{
                    fontSize: 11,
                    fontWeight: 700,
                    color: "#64748b",
                    textTransform: "uppercase",
                    letterSpacing: "0.05em",
                  }}
                >
                  Stage #{idx + 1}
                </span>
                {stages.length > 1 && (
                  <button
                    type="button"
                    onClick={() => removeStage(idx)}
                    style={{
                      background: "none",
                      border: "none",
                      color: "#dc2626",
                      cursor: "pointer",
                      fontSize: 12,
                      fontWeight: 600,
                    }}
                  >
                    ✕ Remove
                  </button>
                )}
              </div>

              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "1fr 1fr",
                  gap: 10,
                }}
              >
                {/* Audit Stage dropdown */}
                <div className={styles.formGroup}>
                  <label className={styles.label}>
                    Audit Stage <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <Select
                    classNamePrefix="rselect"
                    options={AUDIT_STAGE_OPTIONS}
                    value={
                      AUDIT_STAGE_OPTIONS.find(
                        (o) => o.value === stage.stageName,
                      ) || null
                    }
                    onChange={(opt) =>
                      updateStage(idx, {
                        stageName: (opt?.value as string) || "",
                      })
                    }
                    placeholder="Select stage..."
                    isSearchable={false}
                  />
                </div>

                {/* Audit Date */}
                <div className={styles.formGroup}>
                  <label className={styles.label}>Audit Date</label>
                  <input
                    type="date"
                    value={stage.auditDate}
                    onChange={(e) =>
                      updateStage(idx, { auditDate: e.target.value })
                    }
                    className={styles.input}
                  />
                </div>

                {/* Auditor (User) dropdown */}
                <div
                  className={styles.formGroup}
                  style={{ gridColumn: "span 2" }}
                >
                  <label className={styles.label}>
                    Auditor <span style={{ color: "#ef4444" }}>*</span>
                  </label>
                  <Select
                    classNamePrefix="rselect"
                    options={userOptions}
                    value={
                      stage.auditor
                        ? userOptions.find(
                            (o) => o.value === stage.auditor!.id,
                          ) || null
                        : null
                    }
                    onChange={(opt) => {
                      const user = users.find((u) => u.id === opt?.value);
                      updateStage(idx, { auditor: user || null });
                    }}
                    isLoading={usersLoading}
                    placeholder={
                      usersLoading ? "Loading users..." : "Select auditor..."
                    }
                    noOptionsMessage={() => "No users found"}
                    isClearable
                  />
                </div>
              </div>
            </div>
          ))}

          {/* Add stage button */}
          <button
            type="button"
            onClick={addStage}
            style={{
              width: "100%",
              padding: "10px",
              border: "1.5px dashed #cbd5e1",
              borderRadius: 8,
              background: "white",
              color: "#64748b",
              fontSize: 13,
              fontWeight: 600,
              cursor: "pointer",
              transition: "all 0.15s",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.borderColor = "#7c3aed";
              e.currentTarget.style.color = "#7c3aed";
              e.currentTarget.style.background = "#faf5ff";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.borderColor = "#cbd5e1";
              e.currentTarget.style.color = "#64748b";
              e.currentTarget.style.background = "white";
            }}
          >
            + Add Another Stage
          </button>

          {/* Remarks */}
          <div className={styles.sectionHeader} style={{ marginTop: 16 }}>
            <span className={styles.sectionDot} />
            Remarks (optional)
          </div>
          <textarea
            value={remarks}
            onChange={(e) => setRemarks(e.target.value)}
            placeholder="Any additional notes for the report..."
            rows={3}
            className={styles.textarea}
          />
        </div>

        {/* ─── Footer ─── */}
        <div className={styles.modalFooter}>
          <button
            type="button"
            onClick={onClose}
            className={styles.cancelBtn}
            disabled={generating}
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={handleGenerate}
            className={styles.saveBtn}
            disabled={generating}
          >
            {generating ? "Generating..." : "📄 Generate Report"}
          </button>
        </div>
      </div>
    </div>
  );
}
